JavaScript library for event synchronization

let's say I make 3 ajax calls and I want to wait for 3 calls to end before doing anything.

Is there a library for synchronizing multiple asynchronous events in JavaScript? (with or without jQuery event system)

Example:.

var sync = new syncLib(); $('a1').click(sync.newListener()); $('a2').click(sync.newListener()); sync.wait(function(e1, e2) { // fired when both a1 and a2 are clicked or when 10 seconds have passed // e1 and e2 would have properties to know whether or not they timed out or not.. }, 10 /* timeout */)); 

I found this: https://github.com/Ovea/js-sync/blob/master/README.md , but timeouts are not supported. (Let them say that the second ajax call takes too much time, I do not want my synchronization to be suspended, I want to set a timeout of 10 seconds)

I know that I can encode something myself, but I just check here (after searching on it)

Thanks!

EDIT: Since then I have found async: https://github.com/caolan/async

+4
source share
4 answers
 $.when($.ajax("/"), $.ajax("/"), $.ajax("/")).then(function () { alert("all 3 requests complete"); }); 

Documentation

+11
source
+3
source

The .deferred , .when , .then solution mentioned in other answers is much more elegant, but it is also possible to write your own simple solution so that you can see how this can be done manually. You just set the counter for the number of ajax calls you have in flight, and in the success handler for each ajax call, you decrease the counter and start your action when the counter reaches zero.

 function DoMyAjaxCalls(callbackWhenDone) { var numAjaxCalls = 3; // set timeout so we don't wait more than 10 seconds to fire the callback // even if ajax calls aren't done yet var timer = setTimeout(callbackWhenDone, 10*1000); function checkAjaxDone() { --numAjaxCalls; if (numAjaxCalls == 0) { clearTimeout(timer); callbackWhenDone(); } } // first ajax call $.ajax({ url: 'ajax/test1.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); // second ajax call $.ajax({ url: 'ajax/test2.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); // third ajax call $.ajax({ url: 'ajax/test3.html', success: function(data) { // write code to handle the success function checkAjaxDone(); }, error: checkAjaxDone }); } 
+1
source

Here you have the [library] [1] based on jQuery created for this purpose.

In simple cases using $.when() is BEST, but jcon-q-rency allows you to synchronize any sections of asynchronous code.

http://www.megiddo.ch/jcon-q-rency

+1
source

Source: https://habr.com/ru/post/1386384/


All Articles