admin管理员组

文章数量:1291176

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.

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.

Share Improve this question edited Jun 23, 2022 at 21:31 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 26, 2013 at 14:31 catalinuxcatalinux 1,45215 silver badges27 bronze badges 1
  • 3 Use the callback function? – Karl-André Gagnon Commented Jun 26, 2013 at 14:32
Add a ment  | 

2 Answers 2

Reset to default 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();

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'    
});

本文标签: jquerySync two async events in JavaScriptStack Overflow