H.B.
H.B.

Reputation: 178

First promise inside Promise.all() doesn't execute properly

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 ?

Upvotes: 2

Views: 409

Answers (1)

Felix Kling
Felix Kling

Reputation: 816452

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:

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

let counter = 0;
const fn = async(items) => {
  const c = counter++;
  console.log(`enter fn call #${c}`);
  for (item of items) {
    console.log(`fn call #${c} sets item <-`, item);
    await wait(1000)
     console.log(`fn call #${c} reads item ->`, item);
    console.log(item)
  }
}

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

exeAll()


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

Upvotes: 10

Related Questions