Bes-m M-bes
Bes-m M-bes

Reputation: 177

Wait for an ajax to display result

I'm having to trouble to achieve the following task. I have three functions

function f1(param1) {
    var d = $.deferred();
    // ajax call with data param1
   d.resolve(res0, res1);
    return d.promise();
}
function f2(param2) {
    var d = $.deferred();
    // ajax call with data param2
    d.resolve(res2);
    return d.promise();
}

function f3(param3) {
   var d = $.deferred();
   // ajax call with data param3
   d.resolve(res3);
   return d.promise();
}

I'm running them like this :

$.when(f1(param1),f2(pram2),f3(param3)).done(function(res,res2,res3){

});

My requirement is :

if res2 is empty run f2(res[1]). once done display res[0] + f2(res[1]) + res3

else display res[0] + res2 + res3

Is there any one who can help me with this using jQuery/promises?

Thank you

Upvotes: 2

Views: 94

Answers (1)

Alnitak
Alnitak

Reputation: 339786

If I understand you correctly, res and res3 are independent of each other, but res2 may depend on res[1] if the initial call to f2 produced an empty result.

If that happens, you need to call f2 again.

So:

$.when( f1(p1), f2(p2), f3(p3)).then(function(res, res2, res3) {
    if (!res2) {             // substitute appropriate "empty" test
        res2 = f2(res[1]);   // call f2 again, getting a new promise
    }
    return $.when(res, res2, res3);  // create new compound promise
}).done(function(res, res2, res3) {
    // do your stuff
});

The idea being that the inner call to $.when() will automatically resolve if res, res2 and res3 are already "normal" return values, but if res2 is substituted for a new promise the $.when call will wait for that to be resolved before continuing.

Upvotes: 1

Related Questions