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
map
orforEach
.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 — thefor
loop may be different, I haven't had enough coffee to think about it.for
loops actually works differently and will perform the operations in order if you use it in combination withawait
. This is a good blog article showing asynchronous operations used in different types of loops (zellwk.com/blog/async-await-in-loops)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).