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