I want to call a function when previous function is completed. I use async and await, but it does not work :
const getDate = async () => {
await Object.keys(baskets || {}).forEach(vendorCode => {
recalculateBill({
calculateOrder: true,
shop: Tools.pickVendorFiled(baskets[vendorCode]),
shopex: tab === DELIVERY_TYPES.NORMAL
})
})
getShopexInfo({ ids: basketIds })
}
You can use for...in loop instead of Object.keys(baskets || {}).forEach, in which await will work as expected:
async function getDate () {
for (const vendorCode in baskets ) {
await recalculateBill({ calculateOrder: true,
shop: Tools.pickVendorFiled(baskets[vendorCode]),
shopex: tab === DELIVERY_TYPES.NORMAL
});
}
getShopexInfo({ ids: basketIds })
}
Using async/await is quite tricky in forEach loop, maybe you can try switching to for of loop it works great with async/await and you will achieve what you want to Or you also try doing it this way
const getDate = async () => {
Object.keys(baskets || {}).forEach(await(vendorCode) => {
recalculateBill({
calculateOrder: true,
shop: Tools.pickVendorFiled(baskets[vendorCode]),
shopex: tab === DELIVERY_TYPES.NORMAL
})
})
getShopexInfo({ ids: basketIds })
}
The problem here is that you have a loop, await a loop with inside some promises it's tricky, you need to use Promise.all in order to wait all of them to be finished before continuing with the next function.
Promise All take an array of promises (I use .map and not .forEach to return an array of promises), and return a promise itself so you can just await it.
const getDate = async () => {
const basketsArr = Object.keys(baskets || {});
await Promise.all(basketsArr.map((vendorCode) =>
await recalculateBill({
calculateOrder: true,
shop: Tools.pickVendorFiled(baskets[vendorCode]),
shopex: tab === DELIVERY_TYPES.NORMAL
})
))
await getShopexInfo({ ids: basketIds })
}