0

I have a set of functions to run, in sequence, but the first one has an asynchronous sub-function. I want the second highest-level function to run only after the async function completes. Any idea how I do this?

File A:

one();
two(); // I don't want this to run until after one()'s $.ajax success callback

function one() {
    doSomethingElse();
    $.ajax(url, {data: data}, function(){
        // do two();
    });
}
Scott
  • 1,862
  • 1
  • 33
  • 53

3 Answers3

1

Change your function to return the AJAX object:

function one() {
    doSomethingElse();

    return $.ajax({
        url: url,
        data: data
    });
}

And now you do:

one().done(function() {
    two();
});

It's a little cleaner than putting two() directly into the callback.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

Promises are the best option for your purposes

jQuery deferreds and promises - .then() vs .done()

Community
  • 1
  • 1
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
0
function one() {
    doSomethingElse();
    $.ajax(url, {data: data}, function(){
        // do two();
        two();
    });
}

function two(){
alert("here");
}
rahul maindargi
  • 5,359
  • 2
  • 16
  • 23