0

I have the following data

var data = [{user:"somename"}, {user:"anothername"}];

I have this function that processes that that, let say checking user if it exist

function process(user) {
    $.ajax({
        url: 'http://domain.com/api',
        success: function(result) {
            if(result == 'success')
                anotherFunction();
            else 
                console.log('error');
        }
    })
}

function anotherFunction() {
     $.ajax({

        // do stuffs
     })
}

$.each(data, function(k,v){ process(v.user); })

The $.each will try to loop even the process and the anotherFunction hasn't finished yet

Question, what can I do to assure that all functions are finished executing before moving on to another index?

I heard I can use jquery deferred.

Joey Hipolito
  • 3,108
  • 11
  • 44
  • 83

1 Answers1

1

Collect the promises returned by your AJAX function, if necessary post-processing that result with .then so that it calls anotherFunction() which must also return the result of $.ajax.

function process() {
    return $.ajax(...).then(function(result) {
        if (result === 'success') {
             return anotherFunction();
        } else {
             return null;  // this might need to change...
        }
    });
}

function anotherFunction() {
    return $.ajax(...);
}

var promises = [];
$.each(data, function(k, v) {
    promises.push(process(v.data));
}

and then wait for all the promises to be resolved:

$.when.apply($, promises).done(function() {
      // all done here
});

NB: in general it's good practise for an AJAX call to produce a non 2xx return code for errors, rather than an error code within a "successful" HTTP call. This then allows the client side code to use normal AJAX error processing (i.e. .fail callbacks) instead of checking for "errors" within AJAX success processing.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • In principle what Alnitak says is correct but in this question (as originally given), there's all sorts of chained/recursive ajax going on, therefore `process()` needs to be constructed to return a promise of a *final outcome*, produced by a rather tricky `.then()` chain. No time to write it now .... – Beetroot-Beetroot Apr 29 '13 at 11:59
  • Alnitak, good call, though things get a bit messy if the code in the originally phrased (unsimplified) question is to be addressed. – Beetroot-Beetroot Apr 29 '13 at 12:03
  • can i use this? `$.get('http://domain.com/hey.tpl').then(function(result){ // do stuffs. });` – Joey Hipolito Apr 29 '13 at 12:14
  • @JoeySalacHipolito yes, that's legal. You should always try to `return` the result of `$.get`, though. – Alnitak Apr 29 '13 at 12:16