2

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

4
  • Because you're not actually waiting for each item to be inserted with map or forEach.
    – jonrsharpe
    Nov 1, 2021 at 14:20
  • 3
    Your loops all initiate asynchronous operations, and you cannot rely on them finishing in any particular order. Even with the for loop, you probably just got lucky. If you want the ordering at your server to be predictable, send the value and the index. edit — the for loop may be different, I haven't had enough coffee to think about it.
    – Pointy
    Nov 1, 2021 at 14:20
  • 1
    Pointy is right, and luckily I've had some coffee today. for loops actually works differently and will perform the operations in order if you use it in combination with await. This is a good blog article showing asynchronous operations used in different types of loops (zellwk.com/blog/async-await-in-loops)
    – Thejool
    Nov 1, 2021 at 14:45
  • 1
    Even though it works in the way you want it to in for loops, I wouldn't recommend you to use it as it has some performance downsides. The solution proposed by @Pointy is better (you can read more here why that's so: eslint.org/docs/rules/no-await-in-loop).
    – Thejool
    Nov 1, 2021 at 14:54

2 Answers 2

3

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.