Promises:如何并行执行异步方法然后执行方法

Promises: How to execute async methods in parallel then execute method

我正在使用 Q.js 作为承诺。在下面的代码中,每个方法进行 ajax 调用,然后 returns 承诺。一切都按预期进行,每个方法在下一个开始之前执行和完成:

functionOne().then(junctionTwo)
                .then(functionThree)
                .then(doSomethingElse);

然而,我真正想要的是 functionOne、functionTwo 和 functionThree 都同时执行,并且 "doSomethingElse" 应该仅在前 3 个方法完成时执行。

如何使用 promises/Q.js 完成此操作?

您正在寻找 Promise.all : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Promise.all([functionOne(), junctionTwo(), functionThree()]).then(doSomethingElse)

您可以使用现已标准化的 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或浏览器中,没有"simultaneously"因为JS是单线程的(在webWorkers之外,这里没有使用)。但是,如果您的操作是异步的(我认为这是因为它们 return 承诺),那么它们可以同时运行这三个操作,尽管在任何给定时刻只有一个在执行。