deffered对象如何通知其promise它已被解决

How deffered object notifies its promise that it has been resolved?

本文关键字:promise 解决 通知 对象 何通知 deffered      更新时间:2023-09-26

我的意思是,如果有一种方式可以让deffered对象通知其promise状态更改,那么任何人都可以用同样的方式触发附加到promise的回调。我想,我的推理中遗漏了一些东西,但我不知道到底是什么。

jQuery的Deferred返回的promise没有访问解析机制的权限;CCD_ 2中的解析机制可以访问promise和/或其注册的回调。

考虑:

// A D object is a bit like a Deferred
function D() {
  // All of these vars are private
  var state = "pending";
  var resolvedValue = null;
  var callbacks = [];
  // This is our promise, which is private
  var p = {
    then: function(callback) {
      callbacks.push(callback);
    }
  };
  
  // Accessor for our promise
  this.promise = function() {
    return p;
  };
  
  // Resolver -- note the promise object doesn't
  // offer any access to this, just the D
  this.resolve = function(value) {
    if (state === "pending") {
      state = "resolved";
      resolvedValue = value;
      // Note that the resolver has access to the callbacks
      // that the promise registers
      setTimeout(function() {
        callbacks.forEach(function(callback) {
          try {
            callback(resolvedValue);
          } catch (e) {
          }
        });
      }, 0);
    }
  };
}
// Usage
var d = new D();
d.promise().then(function(value) {
  console.log("Got " + value);
});
d.resolve("foo");

也就是说,并不意味着是任何一种真正的递延实现,它只是为了证明递延者如何访问promise,而promise却无法解决递延问题。

您可以在源代码中查看jQuery的Deferred的全部详细信息。但请注意,jQuery的Deferred有点过时了;如今,拥有两个名称独立的对象(DeferredPromise)已经不流行了。相反,JavaScriptPromise对象接受一个初始化函数,初始化函数接收一个可以用来解析promise的解析器函数1


1 仍然涉及两个对象:promise和通过调用初始值设定项创建的执行上下文,但这有点技术性