Dale Jefferson

Dale L. Jefferson

TypeScript, JavaScript, React, React Native

JavaScript Async/Await Promise All Array Destructuring

By Dale Jefferson. Published
JavaScript, Promise, Async Await, TypeScript

I think you will agree with me when I say working with asynchronous code is an important part of modern app development. Using new JavaScript syntax you can drastically improve the readability and performance of your code. In this article, I will show you how to use Promise.all() along with array destructuring.

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.