'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



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sam
Solution 2 Tran Lam