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

后端 未结 10 1495
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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');

    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');

    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.

提交回复
热议问题