0

I am trying to use forEach in array of object and based on the following condition send a request and get that response for using in the other call. Here is the code:

  products.forEach(product => {
    if (
      product.type === 'shows' &&
      product.isSoldOut &&
      product.otherData
    ) {
      delete product.brand.brandId
      product.brand.isTop = true
      const res = apiService.create(product.brand)
      console.log(res)
    }
  })

When I add await const res = await apiService.create(product.brand) here it shows a warning too. How can I use async await in this scenario or is there other way to overcome this issue?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

3 Answers3

0

From await documentation:
"The await operator is used to wait for a Promise. It can only be used inside an async function".
You need to turn your callback in forEach to async:

products.forEach(async (product) => { ... })
peter
  • 583
  • 2
  • 11
  • I don't think this will work as intended, as there is no awaiting the promises. Rather use `map` and await them via `Promise.all`, e.g.: `await Promise.all(producs.map(async (product) =>{...}))` – k0pernikus Mar 04 '21 at 15:49
0

You need to mark the callback as async to allow you to use await. They always have to come in pairs.

e.g.

products.forEach(async (product) => {
    if (
      product.type === 'shows' &&
      product.isSoldOut &&
      product.otherData
    ) {
      delete product.brand.brandId
      product.brand.isTop = true
      const res = apiService.create(product.brand)
      console.log(res)
    }
  })
Dean Potter
  • 55
  • 1
  • 6
-1

Other answers correctly point out that you may just need to mark the method as async. But in this situation where you are firing multiple async calls often you want them to all be fired at the same time, then wait for them to all be resolved. This can be accomplished with Promise.all()

await Promise.all(products.map((product) => {
    if (
      product.type === 'shows' &&
      product.isSoldOut &&
      product.otherData
    ) {
      delete product.brand.brandId
      product.brand.isTop = true
     return apiService.create(product.brand)
    }
  }));
RobPethi
  • 551
  • 9
  • 27