Promise.all is a helper that can handle multiple Promise's at once. Last time we looked at how to use a Promise today we will take that effort a little further and explore how we can handle multiple promises at once.
const somePromise = new Promise((res, rej) => { setTimeout(() => { res('Promise #1') }, 1000) }) const anotherPromise = new Promise((res, rej) => { setTimeout(() => { res('Promise #2') }, 2000) }) Promise.all([somePromise, anotherPromise]).then((...args) => { console.log(args) // consoles: ['Promise #1', 'Promise #2'] after 2 seconds, // which is the longest delay of the two promises })
Console:
As you can see in this example, we first make 2 separate Promise's, we then call Promise.all and pass in an array of Promise's. In this case we passed in our two Promise's, somePromise and anotherPromise. We then need to call .then to get the resolved values.
In the .then call we pass in a callback function, similar to what we do with a standard Promise. The difference here though is that instead of getting a single value returned, we get an array of values that were resolved from the multiple Promise's we passed into Promise.all. The value's in the array are in the same order as the Promise's. So no matter how long each Promise takes, the returned values will always be in the same order.
The final thing we need to look into is error handling.
const somePromise = new Promise((res, rej) => { setTimeout(() => { res('Promise #1') }, 1000) }) const anotherPromise = new Promise((res, rej) => { setTimeout(() => { rej(new Error('Promise #2 threw an error')) }, 2000) }) Promise.all([somePromise, anotherPromise]).then((...args) => { console.log(args) // we don't get here if any Promise throws an error }).catch((err) => { console.log(err.message) // logs out 'Promise #2 threw an error' })
Console:
As you can see this syntax is very similar to a standard Promise. The biggest thing to note is that if any of the Promise's passed in to Promise.all call reject then we default straight to the catch call. So even if you had 9 successful Promise's resolve and only one calls reject, you will not get access to those resolved values. It's all or nothing. Now get out there and start calling Promise.all on everything!
