NodeJS-具有数组承诺的Promise.all()无法按预期返回

时间:2019-03-15 03:10:56

标签: javascript node.js promise

我正在开发一个nodeJS应用程序,并且我有一些以下代码:

let all_result = await Promise.all([list_agrees,list_disagrees]);
    list_agrees = await Promise.all(list_agrees);
    list_disagrees = await Promise.all(list_disagrees);        

res.json({
    result_1:all_result,
    result_2: {
        list_agrees,
        list_disagrees
    }
});

嗨,这是list_agreeslist_disagrees的来源(UserHelper.getUserBasicInfor()返回了诺言)

list_agrees = list_agrees.map(async function(id_user){ 
  return await UserHelper.getUserBasicInfor(req,id_user);
}); 

list_disagrees = list_disagrees.map(async function(id_user){ 
  return await UserHelper.getUserBasicInfor(req,id_user); 
});

现在我收到回复时得到的是

{
    "result_1": [
        [
            {}
        ],
        [
            {}
        ]
    ],
    "result_2": {
        "list_agrees": [
            {
                "avatar_thumbnail": null,
                "full_name": "Đạt Tô",
                "nick_name": "Gầy lọ"
            }
        ],
        "list_disagrees": [
            {
                "avatar_thumbnail": null,
                "full_name": "Gola User ",
                "nick_name": null
            }
        ]
    }
}

我不知道为什么Promise.all([list_agrees,list_disagress])没有返回我期望的结果!

1 个答案:

答案 0 :(得分:2)

Promise.all()处理iterable个承诺集合。

您的问题是list_agreeslist_disagrees都是承诺的数组,而不是承诺本身。

我建议使用类似的方法(不要覆盖原始数组)

const agrees = Promise.all(list_agrees.map(id_user =>
    UserHelper.getUserBasicInfor(req, id_user)))
const disagrees = Promise.all(list_disagrees.map(id_user =>
    UserHelper.getUserBasicInfor(req, id_user)))

现在agreesdisagrees都是在每个UserHelper.getUserBasicInfor()呼叫解决后都会解决的承诺。

因为您的UserHelper.getUserBasicInfor()返回了一个Promise,所以不需要在映射中使用异步函数。

现在您可以使用

const all_result = await Promise.all([agrees, disagrees])
const [agrees_result, disagrees_result] = all_result
res.json({
  result_1:all_result,
  result_2: {
    list_agrees: agrees_result,
    list_disagrees: disagrees_result
  }
})