函数无法解决承诺"/>
异步映射中的异步函数无法解决承诺
我是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))
更多推荐
异步映射中的异步函数无法解决承诺
发布评论