2

I'd like to write this function:

function getResults(nums){
    var results = [];
    for(var i = 0, len = nums.length; i < len; i++){
        var num = nums[i];
        ajaxGet("http://xxx.com/" + num, function(data){
            results.push(data);
        });
    }
    return results;
}    
var results = getResults([12, 22, 34]);

as you can see, because ajaxGet is asynchronous, this won't work. How could I do this properly?

wong2
  • 34,358
  • 48
  • 134
  • 179

4 Answers4

4

You could also tell Ajax to run synchronously

$.ajax({async: false});
var results = getResults();
$.ajax({async: true});
Jason
  • 15,915
  • 3
  • 48
  • 72
  • 1
    https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean – Jason Sep 21 '18 at 17:40
3

You need to return the array using a callback, and call the callback when you receive the last response. (note that responses will not be received in order)

function getResults(nums, callback) {
    var results = [];
    for(var i = 0, len = nums.length; i < len; i++){
        var num = nums[i];
        ajaxGet("http://xxx.com/" + num, function(data){
            results.push(data);
            if (results.length === nums.length)
                callback(results);
        });
    }
}    
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

If you're using jQuery you can set the async flag to false:

function getResults(nums){
    var results = [];
    for(var i = 0, len = nums.length; i < len; i++){
        var num = nums[i];
        jQuery.ajax({
            url: "http://xxx.com/" + num}, 
            async: flase,
            success: function(data){
                results.push(data);
            }
        });
    }
    return results;
}    
var results = getResults([12, 22, 34]);

But if you're doing it this way then your approach is wrong. Go with SLaks answer instead.

jQuery.ajax() API page

Community
  • 1
  • 1
qwertymk
  • 34,200
  • 28
  • 121
  • 184
0
var allresults;

function getResults(nums){
    var results = [];
    for(var i = 0, len = nums.length; i < len; i++){
        var num = nums[i];
        ajaxGet("http://xxx.com/" + num, function(data){
            results.push(data);
            if(results.length == nums.length){
                 resume(results);
            }
        });
    }

}

getResults([12, 22, 34]);

function resume(results){
   allresults =  results;
   ....
   ....
}     

Like others said, use if you are not using jQuery

Diode
  • 24,570
  • 8
  • 40
  • 51