Search posts, tags, users, and pages
can anyone please explain this line to me? Thanks in advance. I am confused that's why.
Promise.all(promise).then(setSelectedDemo);
Hey Moinul Moin, Thanks for asking. Let me try explaining it.
When you have multiple unrelated asynchronous operations to perform, you should use the promise API method called all() or allSettled() to resolve them. You must not use the loop to resolve them one by one.
The method Promise.all executes multiple promises in parallel and returns a new promise. It waits for the execution of all the premises to complete. So, the execution time of the Promise.all method will be the same as the max time taken by an input promise.
In this example, we execute multiple promises using all() method and pass the output of execution to the setSelectedDemo method as an argument. The setSelectedDemo is a method to set the state selectedDemo.
What may be confusing to you is the selectedDemo method not taking any argument explicitly inside then(). You don't have to. Take this example,
You have three promises,
// It resolves with the value red after 1 second
const red = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('red');
}, 1000);
});
// It resolves with the value green after 3 seconds
const green = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('green');
}, 3000);
});
// It resolves with the value blue after 5 seconds
const blue = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('blue');
}, 5000);
});
Now you can use Promise.all() method
Promise.all([red, green, blue]).then(console.log);
Output,
['red', 'green', 'blue']
The Promise.all([red, green, blue]).then(console.log); is same as,
Promise.all([red, green, blue])
.then(function(colors){
console.log(colors)
});
I hope it clarifies. If you are interested to know more about Promises, check this out,
Tapas Adhikary
Educator @tapaScript | Founder CreoWis & ReactPlay - Writer - YouTuber - Open Source