Async Await Promise All Array Destructuring

I’m a big fan of the new Async/Await syntax as it makes asynchronous code easier to read, but there is still a use for our old friend Promise.all().

Let’s pretend you are building a book app and you want to fetch a book with its author and ratings.

Naive implementation

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");

Very clean looking code, but how does it perform?

  • fetchBook: 1 sec
  • fetchAuthor: 1 sec
  • fetchRating: 1 sec
  • Total: 3 sec

The bright people among you will have already noticed that fetchAuthor and fetchRating are independent and could be downloaded concurrently.

Promise all implementation

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]
  }));
};

Not so clean but now we are fetching the author and rating concurrently.

  • fetchBook: 1 sec
  • (fetchAuthor/fetchRating): 1 sec
  • Total: 2 sec

Best of both worlds

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
  };
};

Here we are using array destructuring with await, which in my opinion, vastly improves the readability of the code and we still have the performance improvement from using Promise.all.