.then Executes on 'pending' Rather than Resolved Promise

情到浓时终转凉″ 提交于 2019-12-13 17:16:00

问题


Why does the following code log an array of pending promises? I expect all promises in the array to be resolved and then execute the functions inside the .then methods.

for (let i = 0; i < limit; i++) {
    promiseArray.push(fetch(someUrls[i]))
}

Promise.all(promiseArray)
    .then(responses => responses.map(response => response.text()))
    .then(result => console.log(result))

Thanks in advance


回答1:


That's because response.text() method returns a promise. fetch is a 2-promise thing. One is for the actual request, and the other for conversion.

What you could do is wrap the array.map operation in another Promise.all.

Promise.all(promiseArray)
    .then(responses => Promise.all(responses.map(response => response.text())))
    .then(result => console.log(result))



回答2:


You need to put chained then inside a Promise.all too as the response.text() also returns another promise.

for (let i = 0; i < limit; i++) {
    promiseArray.push(fetch(someUrls[i]))
}

Promise.all(promiseArray)
    .then(responses => Promise.all(responses.map(response => response.text()))) //Needs to wait for all text() promise methods to resolve
    .then(result => console.log(result))

or you can chain promises in your for loop:

for (let i = 0; i < limit; i++) {
    promiseArray.push(fetch(someUrls[i]).then(res => res.text()));
}

Promise.all(promiseArray).then(result => console.log(result))


来源:https://stackoverflow.com/questions/42375974/then-executes-on-pending-rather-than-resolved-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!