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

99
Visualizações
Instruction not waiting properly NodeJS

I was wondering what is the problem here, why is the return statement not waiting to finish the previous instruction? orders are empty, even though I'm logging inside the getOrders to make sure there were data (there is data).

await stores.forEach(async (store) => {
  let arr = await getOrders(store, token, tokenType);
  orders.push(arr);
})
return orders;

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

0

To wait for all promises, you need an array of promises, which you can get using map. Then you need to use Promise.all, so that it will wait for all the promises in that array to complete.

const orders = await Promise.all(
  stores.map(store => getOrders(store, token, tokenType))
);
return orders;

*Edit: rewritten and simplified based on suggestion from @PatrickRoberts

To paraphrase his comment, in the old code when using a separate array with an array.push, the array ordering would be indeterminate. However using the array of results from Promise.all will always match the order of the original array.

about 4 years ago · Juan Pablo Isaza Relatório

0

It's a common misunderstanding that asynchronous callbacks (declared with async and called with await) passed to forEach or map will be executed synchronously or in order. Actually, they are not.

When you check the polyfill of those methods, you'll find a line like this callback.call(T, kValue, k, O);. So, basically, it just execute the callback. If the callback is an asynchronous method, it doesn't wait its execution to be done. Instead, it continue executing other codes.

Let's set an example using your code, let' say this is the callback:

const callback = async (store) => {
  let arr = await getOrders(store, token, tokenType);
  orders.push(arr);
})

When it was passed to forEach:

stores.forEach(callback);

basically, what forEach does is iterating the array, and call callback on each elements. May looks like this

...
loop {
  callback.call(...)
}
...

There is no wait here. However, each time, the code inside your callback is executed synchronously since it's declared with async and called with await, which means after getOrders is resolved and the result is pushed to orders.

So, if you want to execute the callbacks synchronously and in order, you may write a generic for loop.

async function addOrders(){
  for(let store of stores) {
    let arr = await getOrders(store, token, tokenType);
    orders.push(arr);
  }
}

addOrders()

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