Wait for completion after multiple promises in parallel using jQuery

crishushu picture crishushu · Dec 9, 2013 · Viewed 20.5k times · Source

I want to queue multiple asynchronous ajax requests using deferred/promise implementation of jquery:

function doSomething() {
    console.log('doSomething')};

function makeMultiAjaxRequests1() {
    console.log('makeMultiAjaxRequests1')};

function makeMultiAjaxRequests2() {
    console.log('makeMultiAjaxRequests2')};

var step1 = function () { 
    var promise = new $.Deferred().promise();   
    makeMultiAjaxRequests1(); 
    return promise; }

var step2 = function () {
    var promise = new $.Deferred().promise();
    makeMultiAjaxRequests2();
    return promise; } 

step1()
   .then(step2())
   .done(doSomething());

$.when(step1(), 
       step2())
   .done(function () {
    doSomething();
});

Here is the fiddle link. So my question is:

In the pattern where step1 and step2 are executed in parallel, the code does not reach the last handler function. Why?

Answer

Daiwei picture Daiwei · Dec 9, 2013

You need to resolve the deferred obj in step1 and step2

Try this

function doSomething() {
    console.log('doSomething')};

function makeMultiAjaxRequests1(deferred) {
    console.log('makeMultiAjaxRequests1')
    deferred.resolve()};

function makeMultiAjaxRequests2(deferred) {
    console.log('makeMultiAjaxRequests2')
    deferred.resolve()};

var step1 = function () { 
    var deferred = new $.Deferred();   
    makeMultiAjaxRequests1(deferred); 
    return deferred; }

var step2 = function () {
    var deferred = new $.Deferred();
    makeMultiAjaxRequests2(deferred);
    return deferred; } 

step1().then(step2).done(doSomething);

$.when(step1(), step2()).done(function () {
    doSomething();
});