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

200
Vistas
Why does changing parameters inside map async loop only works on first async function call?

I'm trying to understand why the following results happen. I bet there's something to do with the event loop and the fact that all sync code runs before async code, but I cannot apply that knowledge to this example.

// const axios = require('axios');
const array = [1, 2, 3];

const user = {};

const promises = array.map(async (item) => {
  console.log('start');
  user['id'] = item;
  const responseUser = await axios.get(
    `https://jsonplaceholder.typicode.com/todos/${user.id}`
  );
  console.log('middle');
  const responseUser2 = await axios.get(
    `https://jsonplaceholder.typicode.com/todos/${user.id}`
  );
  console.log('end result 2: ', responseUser2.data.id);
  console.log('end result: ', responseUser.data.id);
});

Promise.all(promises);
<script type="text/javascript" src="https://unpkg.com/axios@0.21.4/dist/axios.min.js"></script>

Results:

start
start
start
middle
middle
middle
end result 2: 3
end result: 3
end result 2: 3
end result: 2
end result 2: 3
end result: 1
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This happens because .map will launch the callback for each array element synchronously. Those callbacks are asynchronous, and so each execution of it will return when having evaluated the first await expression. So you get a bunch of suspended executions which each will only continue later from a job in the promise job queue (asynchronously).

Note that your call of Promise.all will execute after all "start" outputs, but it actually isn't doing anything useful, as you don't do anything with the promise that it returns.

Each .map callback will synchronously launch the first HTTP request with the intended user.id (which is the current item from the array), but that URL evaluation is the last synchronous code that executes. By the time the await-ed promises resolve, user.id will have the value of the last item in the array.

Asynchronously, each of the callback executions will then resume. At that time user.id already has the value of the last item in the array. These resumed executions will thus launch their second HTTP request with the last id (3). If your intention was that those second requests would use the same id as the one that preceded it in the code, then you'd have to pass item as URL query, not item.id.

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