What's the difference between a Deferred object and its own promise object?

后端 未结 3 605
悲&欢浪女
悲&欢浪女 2020-12-05 00:34

Let\'s create a simple Deferred object:

defer = $.Deferred( function ( defer ) {
    setTimeout( defer.resolve, 3000 );
});

The above Defer

相关标签:
3条回答
  • 2020-12-05 00:49

    When using the "promise" of a Deferred object the observers (objects waiting for resolve for exemple) dont have direct access to the Deferred object itself, so they can't call, for exemple, the method "Resolve" of that Deferred. It is a way of protecting the original Deferred.

    0 讨论(0)
  • 2020-12-05 00:56

    It creates a "sealed" copy of the deferred value, without the .resolve() and .reject() methods. From the documentation:

    The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.

    It's used when it doesn't make sense for the value to be modified. For example, when jQuery makes an AJAX request it returns a promise object. Internally it .resolve()s a value for the original Deferred object, which the user observes with the promise.

    0 讨论(0)
  • 2020-12-05 01:11

    With Deferred, you can control its state set.

    When it comes to the Promise, you can read state and maybe attach callback. get

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