简体   繁体   中英

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!

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;

You could do this as an alternative:

call1().then(cond2 ? call2 : null).then(cond3 ? call3 : null);

The non-function null will make the promised value to be returned, so the next then callback in the chain will still get the promised value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM