Alex Rivera | Logout

jQuery: wait for function to complete to continue processing?

Asked 2009-09-21T17:54:47.077
17

Hey all. I have, what appears to be, a trivial problem. I have the following JavaScript:

$(function() {
    var r = GetResults();

    for(var i = 0; i < r.length; i++) {
        // Do stuff with r
    }
});

function GetResults() {
   $.getJSON("/controller/method/", null, function(data) {
       return data;
   });
}

Due to the fact that I'm calling a method asynchronously, the script continues executing and when it encounters the for loop, r obviously isn't going to have a value yet. My question is: when I have a method that is doing an asynchronous operation, and I'm dependent on the data it returns back in the main block, how do I halt execution until the data is returned? Something like:

var r = GetResults(param, function() {

});

where the function is a callback function. I cannot move the for loop processing into the callback function of the JSON request because I am reusing the functionality of GetResults several time throughout the page, unless I want to duplicate the code. Any ideas?

Edit
Report

2 Answers

7

Ajax already gives you a callback, you are supposed to use it:

function dostuff( data ) {
    for(var i = 0; i < data.length; i++) {
        // Do stuff with data
    }
};
$(document).ready( function() {
    $.getJSON( "/controller/method/", null, dostuff );
});
answered 2009-09-21T17:59:55.697
3

You could do this:

$(function() {
    PerformCall();        
});

function PerformCall() {
   $.getJSON("/controller/method/", null, function(data) {
       for(var i = 0; i < data.length; i++) {
        // Do stuff with data
       }
   });
}
answered 2009-09-21T17:58:51.143

Your Answer