Search code examples
javascriptjqueryasynchronousdeferred

jQuery deferred: create a chain sequence using conditions


I'm finding myself in the following situation. I need to make 3 asynchronous calls: call2 fires only when call1 is done and call3 fires only when call2 is done (I also need to use the deferred object from jQuery).

function call1() {
   return $.ajax(...);
}

function call2() {
   return $.ajax(...);
}

function call3() {
   return $.ajax(...);
}

Nothing complicated at this point, I could just use the then() function.

call1().then(call2).then(call3)

The problem is that there are 2 conditions (cond2 and cond3) that will determine whether or not call2 and call3 will be made. If I were to describe it using pseudocode it would look like this:

if cond2
  if cond3
    call1().then(call2).then(call3)
  else
    call1().then(call2)
else
  if cond3
    call1().then(call3)
  else
    call1()

I know that I can solve my problem by writing a program that uses this structure, but it just doesn't seem right.

My question is, how would you solve this in an efficient way by using the deferred object from jQuery? Thanks in advance!


Solution

  • This might be what you are looking for:

    var chain = call1();
    if (cond2) chain = chain.then(call2);
    if (cond3) chain = chain.then(call3);
    return chain;