3

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 })
}
Majid M.
  • 4,467
  • 1
  • 11
  • 29
sanaz
  • 176
  • 9
  • 1
    use javascript promises – Vikas Acharya Jan 02 '22 at 08:05
  • Does this answer your question? [What is the difference between JavaScript promises and async await?](https://stackoverflow.com/questions/34401389/what-is-the-difference-between-javascript-promises-and-async-await) – konsolebox Jan 02 '22 at 08:17

3 Answers3

0

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 })
}
0

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 })
}
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
0

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 })
}
Gianmarco
  • 792
  • 2
  • 14
  • 38