Below is the simple code of Promise.all, But the output is confusing the behaviour of Promise.all.
// A simple promise that resolves after a given time
const timeOut = (t) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Completed in ${t}`)
}, t)
})
}
// Resolving a normal promise.
timeOut(1000)
.then(result => console.log(result)) // Completed in 1000
// Promise.all
Promise.all([timeOut(1000), timeOut(2000), timeOut(2000)])
.then(result => console.log(result))
Can some one explain me why the output is not:
Completed in 1000
Completed in 2000
Completed in 2000
['Completed in 1000', 'Completed in 2000', 'Completed in 2000']
This is the output I’m getting:
Completed in 1000
['Completed in 1000', 'Completed in 2000', 'Completed in 2000']
3
Answers
According to the MDN documentation
So you get one single promise, whose value is an array of the originally passed (now resolved) promises.
You added a
.then()
only on one promise:Hence, the appropriate message was printed.
Does this answer your question?
Your output is right – Promise.all returns a promise of an array with results of resolved promises in the array argument. So in
result => console.log(result)
you get an array of all your promises’ results and print it.You need to map the promises and call their
then()
resolution handlers.