我有一个 Proxy
来模拟虚拟对象。此代理的 Getter 返回就绪值。
我发现,如果等待代理,它会导致调用我的代理的“then”属性:
await myProxy
在这种情况下我的代理 getter 应该返回什么?返回代理本身还是对自身的 promise 是个好主意?
例子在这里:
令我困惑的是,如果我await
一个对象,我得到了这个对象,但是如果我await
一个Proxy
,它需要有一个返回自身的“then”属性陷阱。
最佳答案
您可能会考虑返回 undefined
或没有 then
方法的对象,因为 await 递归调用 then
直到解析的对象不再有 then
方法。
举个例子:
(async () => {
let p = new Proxy({ then: undefined }, {
get: (target: any, prop: string, self: any) => {
return (prop in target) ? target[prop] : (...args: any[]) => self;
},
});
let example = await p.myChainable().awaitable().method();
console.log("Result: ", example);
})();
它只返回 "Result: { then: undefined }
,因为我们在 (...args: any[]) => self 中返回了
当然可以用您自己的逻辑替换。self
如果您将目标 { then: undefined }
替换为 { test: "abc"}
之类的内容,则根本不会有任何结果,因为 promise 变成了永远不会实现并且永远不会调用 console.log。
因此作为结论,不 - 我不建议在 then
方法中返回代理对象本身。
关于javascript - 等待代理导致获取 'then' 属性,我应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48338721/