The code below fetches an array from an API, then for each element of this array, retrieves further data.
fetch('https://reqres.in/api/users')
.then(r => r.json()).then(r => {
r.data.forEach(x => {
fetch('https://reqres.in/api/users')
.then(r => r.json()).then(r => {
r.data.forEach(x => console.log(x.id))
})
})
})
I need to perform some action on the data once it is fully retrieved. How to do that?
The problem is that this is a set of Promises which resolve asynchronously. Promise.all() could be used to gather all Promises and work from there - but their amount is not known upfront. In other words, I could use
a = fetch('https://reqres.in/api/users')
b = fetch('https://reqres.in/api/users')
Promise.all([a, b]).then(x => console.log('all resolved here'))
but what is passed to Promise.all() is not known when the script starts.