Smart async/await pattern to execute in parallel (alternative to Promise.all and Promise.allSettled)

Kate Shastakova
2 min readJan 24, 2021

Usually, when we want to run our code in parallel we use either Promise.all() and Promise.allSettled() methods. Unfortunately, we can’t use it in some cases. Cases like when it’s really important for us to execute promises in a specific order and we also have code that prepares some data in between.

Woman is thinking in front of the laptop

Let’s take a look at example where we want to create a book in our database and book should have pages and name.

Typical example with “await”:

// preparing data that takes quite some time
const thousandsOfPages = await getAllPages();
const sortedPages = thousandsOfPages.sort();
// we are waiting for this promise to resolve for quite some time and blocking promise createBook from execution
const bookName = await getBookName();
const bookWithPages = await createBook(sortedPages);

Same example but with Promise.all():

// preparing data that takes quite some time
const thousandsOfPages = await getAllPages();
const sortedPages = thousandsOfPages.sort();
// running promises in parallel
const [bookName, bookWithPages] = await Promise.all([getBookName(); createBook(sortedPages)]);

The problem with example above is that createBook() can be resolved first and getBookName() can be rejected second. And by our original idea, we didn’t want to create a book in our database without making sure we already have a book name. So now we need to handle the case of rolling back a book without a name from our database and we don’t want that.

Example with “promise-on-the-go” or smart async/await:

// getting a promise. We are NOT blocking the code below from execution
const bookNamePromise = getBookName();
// preparing data that takes quite some time
const thousandsOfPages = await getAllPages();
const sortedPages = thousandsOfPages.sort();
// by the time it goes to this line bookNamePromise may probably be already resolved or be very close to it so we don't wait as long as in the first code example
const bookName = await bookNamePromise;
const bookWithPages = await createBook(sortedPages);

Conclusion:

“Promise-on-the-go” approach does not block code from execution as much as “await” and also guarantees the order of execution while Promise.all() and Promise.allSettled() don’t.

--

--

Kate Shastakova

Frontend developer | A strong believer in code best practices