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

91
Visualizações
How to await asynchronous map function?

let me quickly get to the point. I have a function which fetches some user ids. It works very well.

const allIds = await fetchAllIds(someUrl);

Now the problem comes when I want to do something different. I'd like to loop over those ids and do some async await stuff with them. That is, to mainly fetch some data for each one with axios and modify them accordingly.

allIds.map(async (id) => {
  // 1. Fetch some data (try, catch and await)
  // 2. Modify the id based on that data
  // 3. Return the id, namely replace the old one
});

At the end of my code, I simply return allIds. The problem is that it returns them without waiting for the map function to execute completely. I tried different methods and none of it seems to be working. Could you please help me to make it work or perhaps suggest some other possible solutions? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You basically have two problems:

  1. You are ignoring the return value of the map
  2. The map will return an array of Promises and you aren't awaiting them all

So:

const promises = allIds.map(...);
const replacement_ids = await Promise.all(promises);
return replacement_ids;
about 4 years ago · Juan Pablo Isaza Relatório

0

Use this instead.

const newList = await Promise.all(allIds.map(id=>new Promise(async(res)=>{
 // do your async here and get result;
 res(result);
})));

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