4

In my JavaScript App (jQuery) I have two events that are fired asynchronously:

  • widget 1 fires "Event1" when finishes loading
  • widget 2 fires "Event2" when finishes loading

How do I "sync" these two async events in order to "call a method" only after these two events fired.

I would need an approach that works for multiple events also.

1
  • 3
    Use the callback function? Commented Jun 26, 2013 at 14:32

2 Answers 2

12

Use deferred objects.

var deferredObj1 = $.Deferred(),
    deferredObj2 = $.Deferred();

$.when(deferredObj1,deferredObj2).done(function(){
    console.log("They are both done!");
});

// inside the Event1 handler:
deferredObj1.resolve();

// inside the Event2 handler:
deferredObj2.resolve();
Sign up to request clarification or add additional context in comments.

1 Comment

+1 beat me to it, was just reminding myself how this works. Just to add As of Jquery 1.5 ajax calls implement the Promise interface, presuming the asynchronous events in question are ajax this should be exactly what your after...
1

You may want to look at async.js which provides a very interesting and clean way of syncing the execution of asynchronous actions.

For example, the waterfall method allows you to chain asynchronous actions in a sequential order.

Such an execution looks pretty and simple in your real-life code :

async.waterfall([
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
   // result now equals 'done'    
});

3 Comments

waterfall looks like really as jquery $.when or i misunderstood its purpose
This actually chains the calls so that the second runs after the first, the third after the second, etc. This may or may not be desirable, depending on the circumstances. The original code had both tasks started at the same time and able to run in any order.
@cHao sure, in this case nothing prevents you to use async.parrallel if you want your actions to run in parrallel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.