看一个例子:
const getBook = async bookName => {
const book = await fetchBook(bookName);
const author = await fetchAuthor(book.authorId);
const rating = await fetchRating(book.id);
return {
...book,
author,
rating
};
};
getBook("The Wealth of Nations");
使用了 async 和 await,逻辑看起来也很清晰,但是这个例子还是有点小问题。
假设每一个获取数据的操作花费 1s,那么上面请求至少需要花费 3s,但是 fetchAuthor
和 fetchRating
没有任何依赖关系,是可以并发请求的,因此需要进行优化。
可以使用 Promise.all()
来进行并行请求优化。
const getBook = async bookName => {
const book = await fetchBook(bookName);
return Promise.all([
fetchAuthor(book.authorId),
fetchRating(book.id)
]).then(results => ({
...book,
author: results[0],
rating: results[1]
}));
};
恩,目的是达到了,但是看起来代码还是不够简洁,可以进一步利用数组解构来优化。
const getBook = async bookName => {
const book = await fetchBook(bookName);
const [author, rating] = await Promise.all([
fetchAuthor(book.authorId),
fetchRating(book.id)
]);
return {
...book,
author,
rating
};
};
唔,是不是完美了!
PS: origin from https://www.dalejefferson.com/blog/async-await-promise-all-array-destructuring/