Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: wait for function to complete to continue processing?

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?

like image 307
user135383 Avatar asked Sep 21 '09 17:09

user135383


People also ask

How do you wait for a function to complete?

– Async Function-Based Promises: Use the “Await” Function For async function-based promises, you may add the “await” function to stop the function in javascript, until the promise is fulfilled, and then return the result value.

How do you wait for a setTimeout to finish?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.

How do you wait for a function to finish in node JS?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .


2 Answers

move your "do stuff with r" block into your $.getJSON callback. you can't do stuff with r until it has been delivered, and the first opportunity you'll have to use r is in the callback... so do it then.

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

function GetResults() {
   $.getJSON("/controller/method/", null, function(data) {
       for(var i = 0; i < data.length; i++) {
           // Do stuff with data
       }
       return data;
   });
}
like image 173
Ty W Avatar answered Oct 26 '22 16:10

Ty W


I've run into something similar before. You'll have to run the ajax call synchronously.

Here is my working example:

$.ajax({
    type: "POST",
    url: "/services/GetResources",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: '{resourceFileName:"mapedit",culture:"' + $("#lang-name").val() + '"}',
    cache: true,
    async: false, // to set local variable
    success: function(data) {
        localizations = data.d;
    }
});
like image 40
ScottE Avatar answered Oct 26 '22 16:10

ScottE