原文戳这里Async Await Promise All Array Destructuring
我是Async/Await 语法的超级粉丝,因为它使得异步代码更加易读,但是我们的老朋友Promise.all()仍然有用。
让我们假设你正在构建一款book App,你想要取得一本书,作者和评分信息。
简单的实现:
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");
非常干净的代码,但是它的表现如何:
- fetchBook: 1 秒
- fetchAuthor: 1 秒
- fetchRating: 1 秒
- Total: 3 秒
你们中的聪明人已经注意到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]
}));
} ;
代码不是很简洁,但是现在我们已经同时取得作者和评分了。
- fetchBook: 1 秒
- (fetchAuthor/fetchRating): 1 秒
- Total: 2 秒
两全其美:
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
};
};
这里我们使用了数组结构和await,这在我看来,这大大提高了代码的可读性,同时我们仍然使用Promise.all提高了性能。










网友评论