在Promise.all
之后无法访问已解决的承诺的值。如下面的示例所示,res.prop
打印未定义。我想我可以创建一个包装函数,将解析的值推到另一个responses
数组,但这似乎不是一种干净的方法。
(async () => {
const responses = []
let counter = 10
while (counter--) {
responses.push(new Promise(resolve => resolve({prop: 10})))
}
await Promise.all(responses)
for (const res of responses) {
console.log(res) // -> prints Promise {prop: 10}
console.log(res.prop) // -> prints undefined
}
})()
答案 0 :(得分:2)
您永远不会使用await Promise.all(responses)
的返回值。您的诺言的返回值由Promises.all
返回:
(async () => {
const responses = []
let counter = 10
while (counter--) {
responses.push(new Promise(resolve => resolve({prop: 10})))
}
const results = await Promise.all(responses)
for (const res of results) {
console.log(res) // -> prints Promise {prop: 10}
console.log(res.prop) // -> prints undefined
}
})()