Async/await结合map使用返回promise或undefined问题排查求助
问题根因
- 第一个
map传入的异步函数没有显式返回值,所以orderItems数组里的每一个Promise最终resolve的结果都是undefined。你第一个map里的async函数最后执行的是await dataSources.OrderItemAPI.createOrderItem(...),既没有把createOrderItem的返回值return,也没有自己构造orderItem对象返回,async函数默认返回的就是undefined,await之后自然拿到的是undefined。 - 你没有等待第一批异步操作全部执行完成,就直接对
orderItems数组做了第二次map,此时数组里的元素都是pending状态的Promise,直接取orderItem.productId是拿不到的,因为Promise本身没有productId属性。
修复方案
- 第一步:修改第一个map的逻辑,显式返回你需要的orderItem对象,同时用
Promise.all等待所有异步写入操作完成,拿到实际的orderItems结果数组:
const orderItemPromises = 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 // 拿到createOrderItem的返回结果 const orderItem = await dataSources.OrderItemAPI.createOrderItem( orderId, productId, name, quantity, {ttlInSeconds: 60*20} ) // 显式返回orderItem,这样Promise resolve之后就是这个对象 return orderItem }) // 等待所有异步操作完成,拿到实际的orderItem数组 const orderItems = await Promise.all(orderItemPromises)
- 第二步:处理查询关联商品的逻辑,同样用
Promise.all等待所有查询完成:
// 查找每个orderItem对应的商品 const productPromises = orderItems.map(async orderItem => { // 此时orderItem已经是实际的对象,可以直接取productId const product = await dataSources.TransactionAPI.findProductFromOrderItem(orderItem.productId) console.log(product) return product }) const productsCorrespondingToOrderItems = await Promise.all(productPromises)
注意事项
如果你用的环境不支持顶层await,需要把这部分逻辑放在async函数内部执行。如果你的createOrderItem接口本身返回的是空值,可以自己构造需要返回的orderItem结构,比如return { productId, name, quantity },只要把后续需要用到的属性返回即可,不需要完全依赖接口的返回值。
内容的提问来源于stack exchange,提问作者Peter Malik
相关产品推荐
相关产品推荐

