假设我正在执行 3 个 ajax 调用,我想等待这 3 个调用完成后再做某事。
是否有一个库可以同步 JavaScript 中的多个异步事件? (使用或不使用 jQuery 的事件系统)
例如:
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 */));
我找到了这个:https://github.com/Ovea/js-sync/blob/master/README.md ,但不支持超时。 (假设第二次 ajax 调用时间太长,我不希望我的同步被挂断,我想设置 10 秒超时)
我知道我可以自己编写一些代码,但我只是在这里检查(在谷歌搜索之后)
谢谢!
编辑: 从那时起我发现异步:https://github.com/caolan/async
最佳答案
$.when($.ajax("/"), $.ajax("/"), $.ajax("/")).then(function () {
alert("all 3 requests complete");
});
关于用于同步事件的 JavaScript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510437/