-2

I have the following code. I want to take the result of product variable and put them into an array outside of the lineItems.data.map so I can parse the arrary send a request with it's contents. I am a little stuck as to how to do this. I tried creating an empty array and pushing to it but it did not work. Any help would be great. thanks.

The array can be inside the first async function but I can't figure it out at this moment.

   async function (err, lineItems) {

     await lineItems.data.map(async (item) => {
         console.log(item);
         const product = await stripe.products.retrieve(item.price.product);
         return product;
      });

  // I want an array here containing the product

  }
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • Does this answer your question? [How to synchronize an async map function in javascript](https://stackoverflow.com/questions/63754451/how-to-synchronize-an-async-map-function-in-javascript) – Jared Smith Dec 15 '20 at 01:08
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Randy Casburn Dec 15 '20 at 01:18

1 Answers1

3

Right now, lineItems.data.map returns an array of promises. You can't await that directly, but Promise.all will let you await an array of promises just fine!

async function foo(err, lineItems) {
  const arr = await Promise.all(lineItems.data.map((item) => {
    return stripe.products.retrieve(item.price.product);
  }));
  // resolved array should be here
  console.log(arr);
}

foo();

Here's a trivial example showing this all in action:

const prom = (num) => new Promise(res => res(num * 2));

async function foo() {
  const vals = await Promise.all([1, 2, 3].map(x => prom(x)));
  console.log(vals);
}

foo();
Nick
  • 16,066
  • 3
  • 16
  • 32