Search code examples
javascriptpromisedeferred

Javascript then() chaining - which Deferred does the second then() correspond to?


1) I have a chain of jquery then(), like this:

someAjax().then(function(val) { console.log("done 1: " + val); return val + 1; },
                function(val) { console.log("fail 1: " + val); return val + 2; },
                function(val) { console.log("prog 1: " + val); return val + 3; }

         ).then(function(val) { console.log("done 2: " + val) },
                function(val) { console.log("fail 2: " + val) },
                function(val) { console.log("prog 2: " + val) }
         )

I understand that the three functions (three args) of the first then() correspond to the states of the Deferred object from someAjax().

However, I don't understand, what Deferred object do the three functions (args) of the second then correspond to? For example, what if (or is it possible that) each of the three function of the first then() may return its own Deferred object?

I feel like I may misunderstand something in here. Appreciate any clarification.

////////////////////////////////////////////////////

2) I have another chaining like this:

$.getJSON(url).then(
                doneFunction1,
                errorFunction1
            ).then(
                doneFunction2
            });

The doneFunction1 looks like this:

function doneFunction1(val){
   if(val > 1)
      return $.ajax(url2);
}

So this does not always returns a promise, as you see, depending on val. In case it does not return a Promise (say val < 1), how does the second then proceed? Would that cause an error? Because as I understand, there is no Promise to call then() on. My guess is that it may just call the then() of the first Promise of $.getJSON but I may be wrong.

Basically, I am trying NOT to have the second then() at all when `val < 1'. Is it possible?


Solution

  • You can just return a Deferred that is either resolved or rejected

    function doneFunction1(val){
        if(val > 1) {
            return $.ajax(url2);
        } else {
            var def = $.Deferred();
            return def.reject(); // or def.resolve('something'); to hit the success handler
        }
    }
    
    $.getJSON(url).then(
        doneFunction1,
        errorFunction1
    ).then(
        doneFunction2,
        errorFunction2 // only needed if you want to catch the error
    });