我正在开发一个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_agrees
和list_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])
没有返回我期望的结果!
答案 0 :(得分:2)
Promise.all()
处理iterable个承诺集合。
您的问题是list_agrees
和list_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)))
现在agrees
和disagrees
都是在每个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
}
})