【问题标题】:How would I get the product value out of a async function inside a map in javascript我如何从javascript地图中的异步函数中获取产品价值
【发布时间】:2021-03-25 15:51:58
【问题描述】:

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

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

   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

  }

【问题讨论】:

标签: javascript async-await stripe-payments array.prototype.map


【解决方案1】:

现在,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();

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2018-11-18
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多