Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!