Search code examples
javascriptjqueryajaxgulpsuperagent

How to avoid creating a function inside a loop?


I am working on gathering some data using REST calls.

I have the following function which makes calls to a "directory" endpoint that returns me a list of people

I can get more information about their kids.
Now to get their personal information I will have to hit their individual APIs.

var listOfPeople = [];
var numberOfKids = [];

//using superagent    
var req = request.get(ApiPrefix + "/directory");

    req.end(function (err, res) {
                if (err || !res.ok) {
                    console.log("Error obtaining directory");
                } else {

                    listOfPeople.add(res.body);

                    // loop to retrieve all events.
                    for (var i = 0; i < res.body.length; i++) {
                        var personID = res.body[i].id;

                        $.getJSON('/directory/person', {
                                id: personID
                            },
                            function (result) {
                                numberOfKids.add(result);
                            });
                    }
                }
            });

While the above code works perfectly fine, I am getting an error from Gulp watch:

line 67, col 30, Don't make functions within a loop. (W083)
1 error

So, how do I decouple the loop and the AJAX call while expecting the exact same behavior?


Solution

  • I think you can remove for loop and start using Array.forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    Supports all the latest browsers

    In you case, Your for loop should be modified to

    res.body.forEach(function(person){
       var personId = person.id;
       // your getJson call comes here 
    });