你可以这样写:
const responses = await Promise.all([
fetchUserAsync(),
fetchPostsAsync(),
]);
const userResponse = responses[0];
const postsResponse = responses[1];
这很容易吧?但是有一个问题!Promise.all
具有快速失败行为,这意味着,一旦其中一个Promise被拒绝,它就会拒绝。可能您想要一个更强大的解决方案,我们负责处理任何提取的拒绝。幸运的是,有一个解决方案,只需使用async
/await
即可实现,无需使用Promise.all
. 一个工作示例:
console.clear();
function wait(ms, data) {
return new Promise( resolve => setTimeout(resolve.bind(this, data), ms) );
}
/**
* This will run in series, because
* we call a function and immediately wait for it's result,
* so this will finish in 1s.
*/
async function series() {
return {
result1: await wait(500, 'seriesTask1'),
result2: await wait(500, 'seriesTask2'),
}
}
/**
* While here we call the functions first,
* then wait for the result later, so
* this will finish in 500ms.
*/
async function parallel() {
const task1 = wait(500, 'parallelTask1');
const task2 = wait(500, 'parallelTask2');
return {
result1: await task1,
result2: await task2,
}
}
async function taskRunner(fn, label) {
const startTime = performance.now();
console.log(`Task ${label} starting...`);
let result = await fn();
console.log(`Task ${label} finished in ${ Number.parseInt(performance.now() - startTime) } miliseconds with,`, result);
}
void taskRunner(series, 'series');
void taskRunner(parallel, 'parallel');
/*
* The result will be:
* Task series starting...
* Task parallel starting...
* Task parallel finished in 500 milliseconds with, { "result1": "parallelTask1", "result2": "parallelTask2" }
* Task series finished in 1001 milliseconds with, { "result1": "seriesTask1", "result2": "seriesTask2" }
*/
注意:您将需要一个已async
/await
启用的浏览器来运行此代码段(或 nodejs v7 及更高版本)
这样你就可以简单地使用try
/catch
来处理你的错误,并在parallel
函数内部返回部分结果。