It's a common misunderstanding that asynchronous callbacks (declared with async and called with await) passed to forEach
or map
will be executed synchronously or in order. Actually, they are not.
When you check the polyfill of those methods, 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.
Let's set an example using your code, let' say this is the callback:
const callback = async (store) => {
let arr = await getOrders(store, token, tokenType);
orders.push(arr);
})
When it was passed to forEach
:
stores.forEach(callback);
basically, what forEach
does is iterating the array, and call callback on each elements. May looks like this
...
loop {
callback.call(...)
}
...
There is no wait here. However, each time, the code inside your callback
is executed synchronously since it's declared with async
and called with await
, which means after getOrders
is resolved and the result is pushed to orders
.
So, if you want to execute the callbacks synchronously and in order, you may write a generic for
loop.
async function addOrders(){
for(let store of stores) {
let arr = await getOrders(store, token, tokenType);
orders.push(arr);
}
}
addOrders()