在Promise.all数组之后无法访问已解析的promise的值[重复]

问题描述 投票:0回答:1

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
    }
})()
javascript
1个回答
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
    }
})()
© www.soinside.com 2019 - 2024. All rights reserved.