这个问题在这里已有答案:
在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
}
})()
你永远不会使用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
}
})()