Home > Back-end >  First promise inside Promise.all() doesn't execute properly
First promise inside Promise.all() doesn't execute properly

Time:09-17

the wait function is used as a sleep function, fn function takes an array (items), it logs each item and sleeps for a second before logging the next item.

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (item of items) {
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

The problem is the result provided by exeAll function which prints:

B1
A2
B2
B2

But I think it should print something like:

A1
B1
A2
B2

A1 doesn't show at all when the above code is executed. Can anybody explain why ?

CodePudding user response:

for (item of items) { will create an implicit global variable item, i.e. multiple calls to fn will interfere with each other, overwriting item. Properly declare the variable and it works as expected:

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (let item of items) {
  //   ^^^^
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()


We can add more logging to fn to see what happens when in your case:


Strict mode ("use strict";) would have caught that mistake because assigning to an undeclared variable throws an error.

  • Related