0

I have company product packages. I need to get current company product packages. Am trying to get than like this

  const packageIds = user.company.products.forEach(async (prod) => {
      await prod.load('packages')
      const pckgIds = prod.packages.map((packg) => packg.id)
      // i can get ids in here
      console.log(pckgIds)
    })
    // here i get undefined, how can i get here package Ids?
    console.log(packageIds)

I don't understand why I get undefined in packageIds

Boychik
  • 61
  • 7
  • you cant await in a forEach – Matthieu Riegler Aug 11 '22 at 08:18
  • I need await to load prod.load('packages') and the function must not be async where can I do async to load packages? – Boychik Aug 11 '22 at 08:19
  • refer this https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Shivaji Mutkule Aug 11 '22 at 08:20
  • my function must not be async – Boychik Aug 11 '22 at 08:22
  • 1
    You got `paclageIds` undefined, because the `forEach()` returns undefined. If you need a value, you should use `map()` or `reduce()` if products is an array. If it is not, you need to initialize `paclageIds` and update it in the forEach body. – Mario Santini Aug 11 '22 at 08:23
  • first i used map but it's returning Promise { , } – Boychik Aug 11 '22 at 08:25
  • ...but just keep in mind, the `packageIds` you will get is **not complete**, because of the `async` stuff. – Mario Santini Aug 11 '22 at 08:27
  • So `map()` is fine, just return the prod.load(), and you should then pass to `Promise.all()` and pass a callback to the `.then()`. That because you cannot make the current function async. – Mario Santini Aug 11 '22 at 08:29
  • Thanks for your response. I never used Promise.all() really don't know how to do it all. Please if u have time and u give me an example of how can solve this problem. am trying to do this for like 4 hours... – Boychik Aug 11 '22 at 08:37
  • I used promises like this: packageIds = user.company.products.map(async (prod) => { await prod.load('packages') await Promise.all(prod.packages).then((value) => value.map((p) => p.id)) }) but packageIds returns Promise { , – Boychik Aug 11 '22 at 09:05
  • Promise must be await function so how can it work? o O – Boychik Aug 11 '22 at 10:05

0 Answers0