第一个区别 - 快速失败
我同意@zzzzBov 的回答,但Promise.all 的“快速失败”优势并不是唯一的区别。 cmets 中的一些用户问为什么使用Promise.all 是值得的,因为它只在负面情况下更快(当某些任务失败时)。我问,为什么不呢?如果我有两个独立的异步并行任务,第一个需要很长时间才能解决,但第二个在很短的时间内被拒绝,为什么要让用户等待更长的调用完成才能收到错误消息?在实际应用中,我们必须考虑负面情况。但是好的 - 在第一个区别中,您可以决定使用哪个替代方案:Promise.all 与多个 await。
第二个区别 - 错误处理
但在考虑错误处理时,您必须使用Promise.all。无法正确处理由多个awaits 触发的异步并行任务的错误。在负面情况下,无论您在哪里使用 try/catch,您都将始终以 UnhandledPromiseRejectionWarning 和 PromiseRejectionHandledWarning 结尾。这就是设计Promise.all 的原因。当然有人可能会说我们可以使用process.on('unhandledRejection', err => {}) 和process.on('rejectionHandled', err => {}) 来抑制这些错误,但这不是一个好习惯。我在互联网上发现了许多根本不考虑对两个或多个独立异步并行任务进行错误处理的示例,或者以错误的方式考虑它 - 只是使用 try/catch 并希望它会捕获错误。在这方面几乎不可能找到好的做法。
总结
TL;DR:切勿将多个await 用于两个或多个独立的异步并行任务,因为您将无法正确处理错误。对于此用例,请始终使用 Promise.all()。
Async/ await 不是 Promises 的替代品,它只是一种使用 Promise 的漂亮方式。异步代码是用“同步风格”编写的,我们可以避免在 Promise 中出现多个 thens。
有人说,当使用Promise.all() 时,我们不能单独处理任务错误,我们只能处理来自第一个被拒绝的promise 的错误(单独处理可能很有用,例如用于日志记录)。这不是问题 - 请参阅此答案底部的“添加”标题。
示例
考虑这个异步任务...
const task = function(taskNum, seconds, negativeScenario) {
return new Promise((resolve, reject) => {
setTimeout(_ => {
if (negativeScenario)
reject(new Error('Task ' + taskNum + ' failed!'));
else
resolve('Task ' + taskNum + ' succeed!');
}, seconds * 1000)
});
};
当您在正面场景中运行任务时,Promise.all 和多个awaits 之间没有区别。两个示例都在 5 秒后以 Task 1 succeed! Task 2 succeed! 结尾。
// Promise.all alternative
const run = async function() {
// tasks run immediate in parallel and wait for both results
let [r1, r2] = await Promise.all([
task(1, 5, false),
task(2, 5, false)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
// tasks run immediate in parallel
let t1 = task(1, 5, false);
let t2 = task(2, 5, false);
// wait for both results
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
但是,当第一个任务耗时 10 秒成功,第二个任务耗时 5 秒但失败时,发出的错误存在差异。
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
我们应该已经注意到,在并行使用多个awaits 时我们做错了。让我们尝试处理错误:
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!
如您所见,要成功处理错误,我们只需向run 函数添加一个catch,并将带有catch 逻辑的代码添加到回调中。我们不需要处理 run 函数内部的错误,因为异步函数会自动执行此操作 - 承诺拒绝 task 函数会导致拒绝 run 函数。
为了避免回调,我们可以使用“同步样式”(async/await + try/catch)
try { await run(); } catch(err) { }
但是在这个例子中这是不可能的,因为我们不能在主线程中使用await——它只能在异步函数中使用(因为没有人想阻塞主线程)。要测试处理是否以“同步风格”工作,我们可以从另一个异步函数调用 run 函数或使用 IIFE(立即调用函数表达式:MDN):
(async function() {
try {
await run();
} catch(err) {
console.log('Caught error', err);
}
})();
这是运行两个或多个异步并行任务并处理错误的唯一正确方法。您应该避免使用以下示例。
不好的例子
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
我们可以尝试通过几种方式处理上述代码中的错误...
try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled
...没有任何东西被捕获,因为它处理同步代码,但 run 是异步的。
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
……嗯?我们首先看到任务 2 的错误没有被处理,后来它被捕获。在控制台中误导并且仍然充满错误,它仍然无法使用这种方式。
(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
...同上。用户@Qwerty 在他删除的答案中询问了这种奇怪的行为,其中错误似乎被捕获但也未处理。我们会捕获错误,因为run() 在使用await 关键字的行被拒绝,并且可以在调用run() 时使用try/catch 捕获。我们还会收到 unhandled 错误,因为我们正在同步调用异步任务函数(没有 await 关键字),并且此任务在 run() 函数之外运行并失败。
这类似于我们在调用某些调用 setTimeout 的同步函数时无法通过 try/catch 处理错误:
function test() {
setTimeout(function() {
console.log(causesError);
}, 0);
};
try {
test();
} catch(e) {
/* this will never catch error */
}`.
另一个糟糕的例子:
const run = async function() {
try {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
}
catch (err) {
return new Error(err);
}
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
...“只有”两个错误(缺少第 3 个)但没有发现任何错误。
加法(处理单独的任务错误和首次失败错误)
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!
...请注意,在此示例中,我拒绝了这两个任务以更好地演示发生了什么(throw err 用于触发最终错误)。