Promise all behaviour?

Rex

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']
UmbQbify

According to the MDN documentation

The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.

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:

// Resolving a normal promise.
timeOut(1000)
 .then(result => console.log(result)) // Completed in 1000

Hence, the appropriate message was printed.

Does this answer your question?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related