异步映射中的异步函数无法解决承诺

编程入门 行业动态 更新时间:2024-10-18 08:35:59

异步映射中的异步<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数无法解决承诺"/>

异步映射中的异步函数无法解决承诺

我是NodeJS(从C和Python过渡)的新手,并且在嵌套异步/等待方面遇到了严重问题。

下面是我简化的代码段。嵌套的异步函数anAsyncFunction()不能解析结果,执行将离开items.map并返回空结果。

async listAll(){
    try{
        let results = {}
        const items = [
            {'id': 125485, 'name': 'dog'}, 
            {'id': 128893, 'name': 'cat'}
        ]

        await items.map(async(item) => {
            let sub_results = await anAsyncFunction(item.id)
            // console.log(sub_results) ----> Promise { <pending> }
            results[item.id] = { ...item, subResults: sub_results} 
        })

        return { statusCode: 200, body: JSON.stringify(results) }
    }catch(error) {
        return { statusCode: 200, body: JSON.stringify({ message: error.message }) }
    }
}


listAll().then(results => console.log(results))

// OUTPUT: {{'id': 125485, 'name': 'dog', subResults: {}}, {'id': 128893, 'name': 'cat', subResults: {}}} 

我到底在哪里犯错?

回答如下:
async listAll(){
  try{
      let results = {}
      const items = [
          {'id': 125485, 'name': 'dog'}, 
          {'id': 128893, 'name': 'cat'}
      ]
// You are facing issue here, here your map function creates array of promise, while simple await statement can not resolve those, So you need Promise.all API to resolve all promises and await till resolution
      await Promise.all(items.map(async(item) => {
          let sub_results = await anAsyncFunction(item.id)
          // console.log(sub_results) ----> Promise { <pending> }
          results[item.id] = { ...item, subResults: sub_results} 
      }))

      return { statusCode: 200, body: JSON.stringify(results) }
  }catch(error) {
      return { statusCode: 200, body: JSON.stringify({ message: error.message }) }
  }
}


listAll().then(results => console.log(results))

更多推荐

异步映射中的异步函数无法解决承诺

本文发布于:2024-05-07 14:49:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!