Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

66
Vistas
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 ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda