Wait for all promises to resolve in JavaScript

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. …


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

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([await store.getAll(), await 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].


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-02-05T05:00:00+00:00) Wait for all promises to resolve in JavaScript. Retrieved from https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/

MLA
" » Wait for all promises to resolve in JavaScript." flaviocopes.com | Sciencx - Friday February 5, 2021, https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/
HARVARD
flaviocopes.com | Sciencx Friday February 5, 2021 » Wait for all promises to resolve in JavaScript., viewed ,<https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/>
VANCOUVER
flaviocopes.com | Sciencx - » Wait for all promises to resolve in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/
CHICAGO
" » Wait for all promises to resolve in JavaScript." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/
IEEE
" » Wait for all promises to resolve in JavaScript." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/. [Accessed: ]
rf:citation
» Wait for all promises to resolve in JavaScript | flaviocopes.com | Sciencx | https://www.scien.cx/2021/02/05/wait-for-all-promises-to-resolve-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.