-3
for (var i in locations) {
    performRequest(options, function (data) {
        console.log("Got response: " + i + " " + options.host);
        results.push(data.current_observation);
        // return results;
    });
    console.log(results.length)
}

In the above code if log. the results.length in function (data) I m getting result as 1 but when i am logging value outside the performrequest I am getting value as 0 I want to return value of whole array results to the other function Please note perform request is a method which calls json data from a rest api length of locations is 4

underscore
  • 6,495
  • 6
  • 39
  • 78
user2217149
  • 11
  • 1
  • 3

1 Answers1

0

The "Asynchronous" part in AJAX means that, in your case, the execution of the result handler function you pass to performRequest will not be blocking the rest of your program flow. It is scheduled to be executed once the HTTP response comes back from the server for your request.

That's also why you cannot know when console.log(results.length) will exactly be executed. It's very likely that it will most times be executed BEFORE your result handler function: Your result handler function depends on an HTTP request to be complete and is executed asynchronously, while console.log(results.length); does not.

When you want to loop through a collection and for each item synchronously execute an AJAX request, you can call the execution of the next item from your result handler. An easy JQuery-based example could be:

var values = [1, 2, 3, 4, 5];
var count = 0;
var i = -1;
function next() {
    if(i>=values.length) return;
    i++;

    $.get("http://www.example.com/result/" + i, function(data) {
            // do something with your data.
            // notice that at this point you can be sure your asynchronous request
            // was completed and the data definitely is available (or definitely 
            // is unavailable). So you could for example start counting stuff here:
            count++;

            // now that you definitely know that the request is done (successfully or
            // not), you can go ahead with the next one.
            next();
    });
}

This example has some flaws, for example, when you work with a high number of values and short response times, it will just artificially slow down everything.

fjc
  • 5,590
  • 17
  • 36