-1

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?

summerNight
  • 1,446
  • 3
  • 25
  • 52
  • move the function to before the loop... give it a name or var name, and use that instead of the literal. since it can see the global and is passed the dynamic, placement doesn't matter. you might even be able to replace the literal with this literal `numberOfKids.add` or worst-case `numberOfKids.add.bind(numberOfKids)` – dandavis Apr 06 '16 at 21:37

1 Answers1

0

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 
});
LazyDeveloper
  • 599
  • 3
  • 8