为什么用代理解决承诺,然后调用'then'来访问Proxy的getter?
问题描述:
这里有一个小例子:为什么用代理解决承诺,然后调用'then'来访问Proxy的getter?
// Construct a proxy handler with noop getter and setter
const handler = {
get (target, name) { console.error('Getter ' + name + ' should not be called') },
set (target, name, value) { console.error('Setter ' + name + ' should not be called') }
}
// Create a proxy using the handler
const proxy = new Proxy({}, handler)
// Resolve a promise with the new proxy
const promise = new Promise((resolve, reject) => {
resolve(proxy)
})
// Access the proxy from the promise, and the getter for 'then' on the proxy
// is called, not the 'then' method on the promise as expected
promise.then((proxy) => proxy)
而且可运行的例子:https://runkit.com/molovo/possible-promise-proxy-bug
在我的印象中,调用then
正在访问的Promise
的财产,等等Proxy
吸气不应该访问在上面的例子中。这是预期的行为还是错误?而且,如果预期的话,为什么?
答
promise.then自己就好了,并没有调用代理。例如,添加以下行的代码,你不会看到一个额外的使用代理:
const temp = promise.then;
相反,这归结为规范的承诺。当您致电resolve(proxy)
时,承诺解决程序的一部分包括检查proxy.then
的值。然后根据proxy.then是否为函数,它会影响解析过程如何继续。由于正在访问proxy.then,因此您会看到日志语句。
见部分Promise A+ spec 2.3,特别是第2.3.3.1
这也解释了它完美。很好的回复 –