jQuery deferreds and promises - .then() vs .done()

后端 未结 10 1327
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:16

I\'ve been reading about jQuery deferreds and promises and I can\'t see the difference between using .then() & .done() for successful callbacks

相关标签:
10条回答
  • 2020-11-22 07:02

    There is actually a pretty critical difference, insofar as jQuery's Deferreds are meant to be an implementations of Promises (and jQuery3.0 actually tries to bring them into spec).

    The key difference between done/then is that

    • .done() ALWAYS returns the same Promise/wrapped values it started with, regardless of what you do or what you return.
    • .then() always returns a NEW Promise, and you are in charge of controlling what that Promise is based on what the function you passed it returned.

    Translated from jQuery into native ES2015 Promises, .done() is sort of like implementing a "tap" structure around a function in a Promise chain, in that it will, if the chain is in the "resolve" state, pass a value to a function... but the result of that function will NOT affect the chain itself.

    const doneWrap = fn => x => { fn(x); return x };
    
    Promise.resolve(5)
           .then(doneWrap( x => x + 1))
           .then(doneWrap(console.log.bind(console)));
    
    $.Deferred().resolve(5)
                .done(x => x + 1)
                .done(console.log.bind(console));
    

    Those will both log 5, not 6.

    Note that I used done and doneWrap to do logging, not .then. That's because console.log functions don't actually return anything. And what happens if you pass .then a function that doesn't return anything?

    Promise.resolve(5)
           .then(doneWrap( x => x + 1))
           .then(console.log.bind(console))
           .then(console.log.bind(console));
    

    That will log:

    5

    undefined

    What happened? When I used .then and passed it a function that didn't return anything, it's implicit result was "undefined"... which of course returned a Promise[undefined] to the next then method, which logged undefined. So the original value we started with was basically lost.

    .then() is, at heart, a form of function composition: the result of each step is used as the argument for the function in the next step. That's why .done is best thought of as a "tap"-> it's not actually part of the composition, just something that sneaks a look at the value at a certain step and runs a function at that value, but doesn't actually alter the composition in any way.

    This is a pretty fundamental difference, and there's a probably a good reason why native Promises don't have a .done method implemented themselves. We don't eve have to get into why there's no .fail method, because that's even more complicated (namely, .fail/.catch are NOT mirrors of .done/.then -> functions in .catch that return bare values do not "stay" rejected like those passed to .then, they resolve!)

    0 讨论(0)
  • 2020-11-22 07:06

    There is a very simple mental mapping in response that was a bit hard to find in the other answers:

    • done implements tap as in bluebird Promises

    • then implements then as in ES6 Promises

    0 讨论(0)
  • 2020-11-22 07:07

    There is also difference in way that return results are processed (its called chaining, done doesn't chain while then produces call chains)

    promise.then(function (x) { // Suppose promise returns "abc"
        console.log(x);
        return 123;
    }).then(function (x){
        console.log(x);
    }).then(function (x){
        console.log(x)
    })
    

    The following results will get logged:

    abc
    123
    undefined
    

    While

    promise.done(function (x) { // Suppose promise returns "abc"
        console.log(x);
        return 123;
    }).done(function (x){
        console.log(x);
    }).done(function (x){
        console.log(x)
    })
    

    will get the following:

    abc
    abc
    abc
    

    ---------- Update:

    Btw. I forgot to mention, if you return a Promise instead of atomic type value, the outer promise will wait until inner promise resolves:

    promise.then(function (x) { // Suppose promise returns "abc"
        console.log(x);
        return $http.get('/some/data').then(function (result) {
            console.log(result); // suppose result === "xyz"
            return result;
        });
    }).then(function (result){
        console.log(result); // result === xyz
    }).then(function (und){
        console.log(und) // und === undefined, because of absence of return statement in above then
    })
    

    in this way it becomes very straightforward to compose parallel or sequential asynchronous operations such as:

    // Parallel http requests
    promise.then(function (x) { // Suppose promise returns "abc"
        console.log(x);
    
        var promise1 = $http.get('/some/data?value=xyz').then(function (result) {
            console.log(result); // suppose result === "xyz"
            return result;
        });
    
        var promise2 = $http.get('/some/data?value=uvm').then(function (result) {
            console.log(result); // suppose result === "uvm"
            return result;
        });
    
        return promise1.then(function (result1) {
            return promise2.then(function (result2) {
               return { result1: result1, result2: result2; }
            });
        });
    }).then(function (result){
        console.log(result); // result === { result1: 'xyz', result2: 'uvm' }
    }).then(function (und){
        console.log(und) // und === undefined, because of absence of return statement in above then
    })
    

    The above code issues two http requests in parallel thus making the requests complete sooner, while below those http requests are being run sequentially thus reducing server load

    // Sequential http requests
    promise.then(function (x) { // Suppose promise returns "abc"
        console.log(x);
    
        return $http.get('/some/data?value=xyz').then(function (result1) {
            console.log(result1); // suppose result1 === "xyz"
            return $http.get('/some/data?value=uvm').then(function (result2) {
                console.log(result2); // suppose result2 === "uvm"
                return { result1: result1, result2: result2; };
            });
        });
    }).then(function (result){
        console.log(result); // result === { result1: 'xyz', result2: 'uvm' }
    }).then(function (und){
        console.log(und) // und === undefined, because of absence of return statement in above then
    })
    
    0 讨论(0)
  • 2020-11-22 07:07

    There's one more vital difference as of jQuery 3.0 that can easily lead to unexpected behaviour and isn't mentioned in previous answers:

    Consider the following code:

    let d = $.Deferred();
    d.done(() => console.log('then'));
    d.resolve();
    console.log('now');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

    this will output:

    then
    now
    

    Now, replace done() by then() in the very same snippet:

    var d = $.Deferred();
    d.then(() => console.log('then'));
    d.resolve();
    console.log('now');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

    output is now:

    now
    then
    

    So, for immediatly resolved deferreds, the function passed to done() will always be invoked in a synchronous manner, whereas any argument passed to then() is invoked async.

    This differs from prior jQuery versions where both callbacks get called synchronously, as mentioned in the upgrade guide:

    Another behavior change required for Promises/A+ compliance is that Deferred .then() callbacks are always called asynchronously. Previously, if a .then() callback was added to a Deferred that was already resolved or rejected, the callback would run immediately and synchronously.

    0 讨论(0)
提交回复
热议问题