Raja
Raja

Reputation: 249

Continue FOR loop after a function finished

I have a for loop from which a function is called.In that function i have a AJAX call.After ajax finishes then it returns a value to the for loop. then only for loop has to be continued.

for ( var j = 0; j < req.questionId.length; j++) {

    var getanswer = getAnswers();
}

function getAnswers(){

    $.getJSON("getAnswers?question_id="+questionId,function(data){

           return "success";
    });

}

Upvotes: 1

Views: 1867

Answers (8)

SHANK
SHANK

Reputation: 2968

To make use of for loops you need to make your calls synchronous which is not a good practice as it looks like your page is hanged for the duration of request.

Instead make use of a recursive function, which is called as a success callback after your asynchronous call is finished.

// declare in global
var req.questionId = "";
var index = 0;

// declare your recursive function call
function recursiveFunction()
{
    if(index > req.questionId) return false;

    // call your ajax here using global index variable
}

// your ajax function call
function ajaxCall
{
    $.ajax({
    url: "getAnswers?question_id=" + questionId,
    dataType: 'json',
    success: function (data) {
        ret = "success";

        // call your recursive function here
        recursiveFunction();
    }
});
}

Now ajax call is async and for loop is implemented by recursive calls.

Hope that helps.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

An abstract implementation of the solution could look like

getAnswers(array, complete) {
    if (array.length == 0) {
        complete();
    }

    var questionId = array.shift()
    $.getJSON("getAnswers?question_id=" + questionId, function (data) {
        //do what ever you want to do with data

        //call the next question
        processQuestions(array, complete)
    });
}

getAnswers(req.questionId, function(){
    //do something when all questions are completed
})

Upvotes: 0

Glitch Desire
Glitch Desire

Reputation: 15061

AJAX runs ASYNCHRONOUSLY by default

Your AJAX functions run asynchronously, so they don't interrupt the flow of your JavaScript code. What this means is that they send a request, then wait for a response and process whatever you put in your success function. All the while, the rest of the code keeps running.

Your best option is probably to take whatever you're doing with the AJAX return out of the for loop and pass it into the success parameter of your AJAX query, like this:

$.getJSON("getAnswers?question_id="+questionId,function(data){
    ... handle data, parse it, write to page etc ...
});

You can make AJAX run in a synchronous manner with a different call syntax, but even from here you'll struggle to get a return out of it:

$.ajax({
    dataType: "json",
    url:      url,
    data:     data,
    success:  success,
    async:    false
});

Without knowing more about your code and what you're doing with the return, I can't say for certain how you should approach this, but 99 times out of 100 running an AJAX request in the way you're doing it is poor software engineering.

Upvotes: 1

letiagoalves
letiagoalves

Reputation: 11302

Since $.getJSON is asynchronous I think you need go with another approach.

Something like this this:

for (var j = 0; j < req.questionId.length; j++) {
    var getanswer = getAnswers();
}

function getAnswers() {
    var ret = false;
    $.ajax({
        url: "getAnswers?question_id=" + questionId,
        dataType: 'json',
        async: false,
        success: function (data) {
            ret = "success";
        }
    });
    return ret;
}

This way you are forcing jQuery to run your request code synchronously.

Upvotes: 0

Moazzam Khan
Moazzam Khan

Reputation: 3170

You need to make the call using $.ajax() to it synchronously, like this:

for ( var j = 0; j < req.questionId.length; j++) {

    var getanswer = getAnswers();
}

function getAnswers(){
    var result;
    $.ajax({
      url: "getAnswers?question_id="+questionId,
      dataType: 'json',
      async: false,
      success: function(data) {
         result="success";
      }
    });
    return result;
}

Upvotes: 1

htxryan
htxryan

Reputation: 2961

What I think you're looking for is a synchronous call. Check the answer here: getJSON Synchronous

By default, getJSON executes asynchronously, which means the code execution continues without waiting for a response.

Upvotes: 0

Pranav Kale
Pranav Kale

Reputation: 639

You need to make the ajax call synchronous to use it. Use following code:

$.ajaxSetup({
        async: false
    });

Upvotes: 0

HammerNL
HammerNL

Reputation: 1841

The jQuery getJSON call is asynchronous, which means that the call is executed in the background. So you call to $.getJSON returns immediately.

You will have to provide getJSON with a "ready-function" (see the documentation), which is called when the AJAX call is returned.

Alternatively (though I would advise against it), you can force jQuery to make a synchronous AJAX call, it will wait for a reply before continuing. Check out the jQuery documentation on that.

HTH

Upvotes: 3

Related Questions