Home > OS >  i want to Call a function after previous function is complete reactjs
i want to Call a function after previous function is complete reactjs

Time:01-02

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

CodePudding user response:

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

CodePudding user response:

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 ) {
    const result = await recalculateBill({
                             calculateOrder: true,
                             shop: Tools.pickVendorFiled(baskets[vendorCode]),
                             shopex: tab === DELIVERY_TYPES.NORMAL
                           });
  }
  getShopexInfo({ ids: basketIds })
}
  • Related