Reputation: 9
I have array that contain urls. Firstly I need to fetch first and second urls simultaneously and when one of this will be resolved, i will fetch next url. Repeat while all urls wont be fetched. How can i do this ?
Upvotes: -1
Views: 1255
Reputation: 707308
You don't show any code, so I'll have to provide a generic example. fetch()
returns a promise. If you want to run a loop sequentially waiting for the promise of each fetch()
operation, then the simplest way to do that is with async
and await
:
async function someFunc(array) {
for (let item of array) {
let result = await fetch(/* pass arguments here using item */);
// process result here
}
return someValue; // this becomes the resolved value of the promise
// the async function returns
}
// usage
// all async functions return a promise
// use .then() on the promise to get the resolved value
someFunc(someArray).then(results => {
console.log(results);
}).catch(err => {
console.log(err);
});
Upvotes: 2