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

149
Visualizações
Why the order of array when insert it into database using map, forEach and for loop is different

I have an array [1,2,3,4,5] and when insert into database I except to receive result be like [1,2,3,4,5] in database. But only loop for give me an expected result, map() and forEach() always give me disorder array like [1,3,4,5,2] or [4,3,2,5,1] and so on. This is my code:

arrayChild.map(async item => {
    await this.repository.save(item)
});

arrayChild.forEach(async item => {
    await this.repository.save(item)
});

for (let i = 0; i < arrayChild.length; i++) {
    await this.repository.save(arrayChild[i])
}

Please give me the reason. Thank for your attention

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

0

because map and forEach methods don't handle the asynchronous function you passed in an async await way.

When you check the polyfill of both method, 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.

So, when you save your array of data to database, your callbacks inside map & forEach just issue a few query, the final order of database's execution may be uncertain.

about 4 years ago · Juan Pablo Isaza Relatório

0

Because await doesn't work in forEach and map methods, it is not asynchronous. Therefore, when you use await in forEach or map methods to save data into db, it will run the loops silmutaneously and the results will be in disordered way.

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