异步映射中的异步功能无法解决承诺

时间:2020-05-14 17:24:24

标签: node.js async-await

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

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

function Myrand(max,min){
    arr=[];
    for (i = 0; i < max; i++) {
        x = Math.floor( Math.random() * max) + min;
        if(arr.includes(x) == true){
            i=i-1;
        }else{
            if(x>max==false){
                arr.push(x);
            }
        }
    }
    return arr;
}
console.log(Myrand(5,1));

我到底在哪里犯错了?

2 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:1)

有问题的代码是这部分

  await items.map(async(item) => {
          ....
        })

您正尝试等待一系列的承诺,而不是承诺。 要解决此问题,您应该像这样使用Promise.all

 await Promise.all(items.map(async(item) => {
         ....
       }))