繁体   English   中英

如何从 javascript 中的 map 中的异步 function 中获取产品价值

[英]How would I get the product value out of a async function inside a map in javascript

我有以下代码。 我想获取产品变量的结果并将它们放入 lineItems.data.map 之外的数组中,这样我就可以解析数组并发送带有其内容的请求。 我对如何做到这一点有点困惑。 我尝试创建一个空数组并推送到它,但它不起作用。 任何帮助都会很棒。 谢谢。

该数组可以在第一个异步 function 内,但我现在无法弄清楚。

   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

  }

现在, lineItems.data.map返回一组承诺。 你不能直接await ,但是Promise.all会让你等待一系列的承诺就好了!

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();

这是一个简单的例子,展示了这一切:

 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM