Anthony Schanen
Anthony Schanen

Reputation: 96

What is the 'correct way' of using fetch() within a for loop

I'm having trouble understanding where my for loop needs to go if I'm fetching with it. I have code that is dependent on all the promises being resolved and JSON data being saved to testarray

I have created a variety of attempts, but they don't solve my problem. One is to for loop the call to a function which has a promise within it.

function getData() {
        return new Promise(function (resolve, reject) {
            fetch(url[i])
                .then((resp) => resp.json())
                .then(function (data) {
                    buffer = data;
                    resolve();
                });
        });
}

for (i = 0; i <2; i++){
    getData().then(function(){
    testarray.push(buffer);
    //do stuff with testarray
    })
    
}

but this doesn't work because I cant use the data that is pushed on testarray, unless its in the for loop block.

If I put the for loop around the promise or around the fetch, I have a similar problem.

So my question is. If you use a for loop to fetch a variety of JSONs with an API call, how do you use the data outside the for loop? The actions I need for the data require all of it to be done.

I'm confused because I feel like Javascript is forcing me to put the action or code associated with the data where my comment is. Is this normal?

Upvotes: 1

Views: 500

Answers (1)

Alejandro Gomez
Alejandro Gomez

Reputation: 80

You have the Promise.all API to tackle your problem. This method will execute all the promises passed to it and will no resolve until all of them its ok.

This, together with async/await, could be a great solution for your problem:

async function forFetch(){
    let urls = [/* your urls */], fetches = [];

    for(let url of urls){ 
        fetches.push(fetch(url));
    }
    
    let results = await Promise.all(fetches);
    return results; //do whatever you want with your results like converting them to json.
}

Upvotes: 1

Related Questions