我的意思是,如果延迟对象可以通过某种方式通知其关于状态更改的 promise ,那么任何人都可以通过相同的方式触发附加到 promise 的回调。我想,我在推理中遗漏了一些东西,但我无法弄清楚到底是什么。
最佳答案
jQuery 的Deferred
返回的promise 无法访问解析机制; Deferred
中的解析机制确实可以访问 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");
这不是意味着任何类型的真正的 Deferred 实现,它只是为了演示 deferred 如何在 promise 无法解析 deferred 的情况下访问 promise。
您可以查看 jQuery 的 Deferred
的完整详细信息 in the source .但是请注意,jQuery 的 Deferred
有点过时了;如今,拥有两个具有名称的独立对象(Deferred
与 Promise
)已经过时了。相反,JavaScript Promise
对象接受一个初始化函数,而该初始化函数接收一个可用于解析 promise 的解析器函数。1
1 仍然涉及两个对象:promise 和通过调用初始化程序创建的执行上下文,但这有点技术性......
关于javascript - 延迟对象如何通知它已解决的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38653549/