Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda