beginner React/Javascript: callback hell

mokiliii Lo

I'm trying to fetch some data, and THEN fetch some other data. Problem is, there's a loop with a timeout in the mix, which makes everything so complicated. And it doesn't work.

In the order, what I'm triying to do:

  1. Loop through listOfGroups and fetch one or many get request to my backend
  2. When that is done, fetch one time another get request

So, here's my code:

var i = 0;
var arrayOfPostURL = [];
isFinished = false;
while (isFinished == false)
    if(i == listOfGroups.length) {
        return fetch("/update_db_fcb_groups/" + theID + "/" + arrayOfPostURL).then((response) => {
                    response.json().then((data) => {
                        this.setState({onFcbGroups: arrayOfPostURL})
                        isFinished = true;
                    });
                });
    }
    if(i<listOfGroups.length){
        setTimeout(function(){
                fetch("/post_to_fcb_group/" + listOfGroups[i] + "/" + theID).then((response) => {
                    // console.log(response);
                    response.json().then((data) => {
                        arrayOfPostURL.push("+" + data.url)
                        i++;
                    });
                });
                // console.log(arr[i])
        },5000)
    }
}

This code even freezes the browser (Google Chrome) !

Any ideas?

Luke

It looks like you're using a while loop when you could be using a for.

var arrayOfPostURL = [];

for (let group of listOfGroups) {
    setTimeout(function() {
        fetch("/post_to_fcb_group/" + group + "/" + theID).then((response) => {
            response.json().then((data) => {
                arrayOfPostURL.push("+" + data.url)
            });
        });
    }, 5000)
}

fetch("/update_db_fcb_groups/" + theID + "/" + arrayOfPostURL).then((response) => {
    response.json().then((data) => {
        this.setState({onFcbGroups: arrayOfPostURL}) 
    }); 
});

Breaking your code down like this reveals a couple other issues.

  1. Your setTimeouts will all finish around the same time. You're just queueing a bunch of fetches that will each take place 5 seconds after they were queued. If you meant to wait 5 seconds between each fetch, this is not the way to do so.
  2. Your final fetch concatenates an array into the URL. That will end up looking something like "/your/url/+url1,+url2". Is that what you intended? It's a fairly unusual URL schema. You might want to change that call to a POST or PUT and pass in a JSON array in the body.
  3. Because you're calling setTimeout on all of your fetches, your final fetch will actually finish when the loop completes which could be before any of the other fetches execute. You likely want to use Promise.all or something similar.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related