我使用Q.js作承诺。在下面的代码中,每个方法都进行一次ajax调用,然后返回一个promise。一切都按预期工作,每个方法在下一个开始之前执行并完成:
functionOne().then(junctionTwo)
.then(functionThree)
.then(doSomethingElse);
然而,我真正想要的是functionOne,functionTwo和functionThree都可以同时执行,并且" doSomethingElse"只有在前3种方法完成后才能执行。
你如何使用promises / Q.js实现这一目标?
答案 0 :(得分:1)
您正在寻找Promise.all
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Promise.all([functionOne(), junctionTwo(), functionThree()]).then(doSomethingElse)
答案 1 :(得分:1)
您可以使用现在标准化的Promise.all()
告诉您何时完成了一系列承诺:
Promise.all([functionOne(), functionTwo(), functionThree()]).then(function(results) {
// all are done here
doSomethingElse();
}).catch(function(err) {
// error in at least one promise here
});
或者,如果您仍在使用Q库语法,那么您可以使用Q.all()
执行相同的操作。
Q.all([functionOne(), functionTwo(), functionThree()]).then(function(results) {
// all are done here
doSomethingElse();
}).catch(function(err) {
// error in at least one promise here
});
你应该知道在node.js或浏览器中,没有“同时”,因为JS是单线程的(在webWorkers之外,这里没有使用)。但是,如果你的操作是异步的(我假设它们返回了promises),那么它们可以同时在三个飞行中,尽管在任何给定时刻只有一个正在执行。