4

Having a really hard time with this issue, and I know $.when() can be used like so (with multiple AJAX statements) to promise you when they have all finished.

http://jsfiddle.net/M93MQ/

    $.when(
        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 1 complete')
          }
        }),

        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 2 complete')
          }
        })
    ).then( function () { alert('all complete'); });

But this only works with raw $.ajax(), is there anyway to have this same functionality with function calls, that in turn have the ajax inside them (and other random logic) ?

Pseudo-code idea:

    // The functions having the AJAX inside them of course
    $.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () {
        alert('all complete'); 
    });
1
  • 1
    What you're passing to $.when() is the return value of the function calls made to $.ajax; you're not passing it functions, in other words. By the time that $.when() is called, the ajax operations have already started. Commented Jan 31, 2013 at 21:16

1 Answer 1

6

Sure, have the function return a promise object.

function ajaxFunctionOne() {
    return $.ajax(...)
}
function ajaxFunctionTwo() {
    var dfd = $.Deferred();
    // on some async condition such as dom ready:
    $(dfd.resolve);
    return dfd.promise();
}

function ajaxFunctionThree() {
    // two ajax, one that depends on another
    return $.ajax(...).then(function(){
        return $.ajax(...);
    });
}   

$.when(ajaxFunctionOne(),ajaxFunctionTwo(),ajaxFunctionThree()).done(function(){
    alert("all complete")
});
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing... Thanks Kevin, I'm a dummy and I wasn't invoking the functions in the $.when(functionName <-- no () plus, I didn't know it had to be within the return of it! Cleared it right up, your the man now dawg.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.