skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You need to map the promises and call their then() resolution handlers.

    // 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)]
        .map(p => p.then(msg => {
          console.log(msg) // map and call `then()` which receives the message
          return msg // make sure you return the original message
        })))
     .then(result => console.log(result))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search