Promise.all数组后无法访问已解决的Promise的值

时间:2019-03-14 15:06:56

标签: javascript

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
    }
})()

1 个答案:

答案 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
    }
})()