我如何从 javascript 中地图内的异步函数中获取产品值
How would I get the product value out of a async function inside a map in javascript
我有以下代码。我想获取 product 变量的结果并将它们放入 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
}
现在,lineItems.data.map
returns 一系列承诺。你不能直接 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();
我有以下代码。我想获取 product 变量的结果并将它们放入 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
}
现在,lineItems.data.map
returns 一系列承诺。你不能直接 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();