โ† flaviocopes.com

Wait for all promises to resolve in JavaScript

Published Feb 05 2021

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! โœจ

Sometimes we need to wait for a promise to resolve, and we also need to wait for another promise to resolve.

Something like this:

const values = await store.getAll()
const keys = await store.getAllKeys()

This works but itโ€™s not ideal. First weโ€™re waiting for the first call to be resolved, then we start the second.

I want to start both first, then I want to wait until both finished. Not a millisecond more.

The solution is to wrap all in a await Promise.all() call, like this:

const data = await Promise.all([store.getAll(), store.getAllKeys()])

Once this is resolved, we can access the first call value using data[0] and the second call return value with data[1].



I write books for developers ๐Ÿ‘‡๐Ÿผ

© 2023 Flavio Copes Flavio Copes made in Italy ๐Ÿ‡ฎ๐Ÿ‡น using Notion to Site Notion to Site