Scott
Scott

Reputation: 1872

jquery - do something after everything is done -

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();
    });
}

Upvotes: 0

Views: 5016

Answers (3)

rahul maindargi
rahul maindargi

Reputation: 5625

function one() {
    doSomethingElse();
    $.ajax(url, {data: data}, function(){
        // do two();
        two();
    });
}

function two(){
alert("here");
}

Upvotes: 0

Blender
Blender

Reputation: 298166

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.

Upvotes: 1

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14225

Promises are the best option for your purposes

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

Upvotes: 0

Related Questions