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
2 Answers
Reset to default 12Use 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
版权声明:本文标题:jquery - Sync two async events in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741506394a2382345.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论