One of the common usage of Promises is to get some data from the server.
If some application requires data from different servers then we need to send multiple requests parallelly to these different servers. As these requests are asynchronous, parallel and independent from each other, it will be difficult to tell at which point we have the data from all the sources.
We can use Promise.all() to work with multiple promises parallelly.
We can pass an array of two or more promises to Promise.all() which returns a Promise, which gets resolved when all the promises passed to it gets resolved, or, rejected when any promise that was passed gets rejected.
When you execute the above code, resultPromise will wait till both the promises supplied to it gets resolved. We will get [ ‘Resolved after 1000ms’, ‘Resolved after 5000ms’ ] after 5 secs. Even though the first promise gets resolved after 1 sec, it will wait until the result of the second promise.
Instead of resolving inside first promise, if we reject, then the resultPromise will get rejected after 1 sec. It do not wait for the result of the second promise which is called as ‘Fail-Fast’.
One thing we can note here is, even though the resultPromise is getting rejected and we are getting the message ‘Rejected after 1000ms’ after 1 sec, the program execution itself was continuing and gets stopped only after 5 secs. That is because of the active setTimeout and not because of the promises.
Passing some Static Data to Promise.all()
Instead of passing all promises we can also pass some static data to Promise.all()
If you execute the above code, you will get [ ‘Rejected after 1000ms’, ‘how to JS’ ] after 1 second.
What is the purpose of sending static data to Promise.all() ?
This can be useful when you are working with multiple scopes or if the scope of the static data is not available to the resultPromise successful callback function.
Passing Only Static data to Promise.all()
We can pass only static data to Promise.all()
What is the purpose of sending only static data to Promise.all() ?
If you do not want to execute something immediately but want to execute in the next tick, then you can use this.
When you run the above code, first you get ‘Program end’ and then the message from the Promise.
Also note that the promises gets executed before ‘time’ events.
When you run the above code first you get ‘Program end’, then the message from the Promise, then ‘inside timeout’