TL;DR
用于并行函数调用,发生错误时应答行为不正确。Promise.all
首先,一次执行所有异步调用并获取所有对象。其次,在对象上使用。这样,当您等待第一个解析时,其他异步调用仍在进行中。总体而言,您只会等待最慢的异步调用。例如:Promise
await
Promise
Promise
// Begin first call and store promise without waiting
const someResult = someCall();
// Begin second call and store promise without waiting
const anotherResult = anotherCall();
// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];
// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise
JSbin 示例:http://jsbin.com/xerifanima/edit?js,console
警告:无论调用是在同一行还是在不同的线路上,只要在所有异步调用之后发生第一个调用即可。请参阅JohnnyHK的评论。await
await
更新:根据@bergi的答案,此答案在错误处理中具有不同的时间,它不会在错误发生时抛出错误,而是在执行所有承诺之后。我将结果与@jonny的提示进行比较:,检查以下代码片段[result1, result2] = Promise.all([async1(), async2()])
const correctAsync500ms = () => {
return new Promise(resolve => {
setTimeout(resolve, 500, 'correct500msResult');
});
};
const correctAsync100ms = () => {
return new Promise(resolve => {
setTimeout(resolve, 100, 'correct100msResult');
});
};
const rejectAsync100ms = () => {
return new Promise((resolve, reject) => {
setTimeout(reject, 100, 'reject100msError');
});
};
const asyncInArray = async (fun1, fun2) => {
const label = 'test async functions in array';
try {
console.time(label);
const p1 = fun1();
const p2 = fun2();
const result = [await p1, await p2];
console.timeEnd(label);
} catch (e) {
console.error('error is', e);
console.timeEnd(label);
}
};
const asyncInPromiseAll = async (fun1, fun2) => {
const label = 'test async functions with Promise.all';
try {
console.time(label);
let [value1, value2] = await Promise.all([fun1(), fun2()]);
console.timeEnd(label);
} catch (e) {
console.error('error is', e);
console.timeEnd(label);
}
};
(async () => {
console.group('async functions without error');
console.log('async functions without error: start')
await asyncInArray(correctAsync500ms, correctAsync100ms);
await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);
console.groupEnd();
console.group('async functions with error');
console.log('async functions with error: start')
await asyncInArray(correctAsync500ms, rejectAsync100ms);
await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);
console.groupEnd();
})();