Skip to content

Instantly share code, notes, and snippets.

@zxhfighter
Created February 27, 2018 03:38
Show Gist options
  • Save zxhfighter/52f6e96f1d2b45c356524859e234c8d7 to your computer and use it in GitHub Desktop.
Save zxhfighter/52f6e96f1d2b45c356524859e234c8d7 to your computer and use it in GitHub Desktop.
using destruction with Promise.all()

使用解构改善 Promise.all 可读性

使用 async 和 await 来优化流程

看一个例子:

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,但是 fetchAuthorfetchRating 没有任何依赖关系,是可以并发请求的,因此需要进行优化。

使用 Promise.all() 来优化性能

可以使用 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]
  }));
};

恩,目的是达到了,但是看起来代码还是不够简洁,可以进一步利用数组解构来优化。

使用数组解构来提高 Promise.all() 的可读性

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment