【发布时间】:2021-12-05 08:49:41
【问题描述】:
我一直在努力理解这有什么问题,但我仍然无法意识到我做错了什么。 我正在尝试使用此 .map() 函数将用户购物篮中的每个项目作为 orderItem 添加到数据库中(数据库中的 orderItem 对应于产品,这与问题并不真正相关,但如果你是难以理解操作):
const orderItems= orderData.map(async product=>{
const productId=product.id.slice(0,product.id.length-5)
const targetProduct=await dataSources.ProductAPI.product(productId)
const name=targetProduct.name
const quantity=218327
await dataSources.OrderItemAPI.createOrderItem(orderId,productId,name,quantity,{ttlInSeconds:60*20})
})
然后,我尝试将上述数组 orderItems 中的每个 orderItem 映射到数据库中的实际产品,如下所示:
//我们找到每个orderItem对应的产品
const productsCorrespondingToOrderItems= orderItems.map(async orderItem=>{
const trial=await orderItem
console.log(trial) <--- returns undefined
// OR just logging orderItem returns a promise
await dataSources.TransactionAPI.findProductFromOrderItem(orderItem.productId).then(x=>console.log(x))
})
我已经检查了订单商品中的每件商品,看起来还不错。问题是productsCorrespondingToOrderItems 中的每个orderItem 在我只是记录它时返回一个promise,或者如果我等待它则返回undefined。我真的不明白,我做错了什么?非常感谢!
【问题讨论】:
-
你没有从你的
map()回调中返回任何东西 -
@RobbyCornelissen 非常感谢您的快速回复!我不知道我是怎么错过的,现在就试试看!
-
您尝试做的事情没有多大意义。
Array.map不适用于异步代码。Array.map仅用于同步代码。如果你想使用async/await进行顺序循环,你应该使用for或for ... of循环。如果你想做并行异步操作,你应该使用Array.map创建你的 Promise,然后使用Promise.all等待它们。 -
@nicholaswmin - 这对于我们
map来说是非常常见的,带有async回调来产生一系列你然后等待的承诺(例如,通过@987654336 @ 或其他 Promise 组合方法之一)。 -
@T.J.Crowder 确实是的,但我已经在评论的最后部分提到了这一点。
标签: javascript node.js asynchronous async-await