最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin23浏览0评论

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

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

我是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))
发布评论

评论列表(0)

  1. 暂无评论