Reputation: 455
I have a Proxy
to mimic a virtual object. Getter of this proxy returns ready values.
I have discovered, that if the proxy is awaited, it leads to calling of the 'then' property of my proxy:
await myProxy
What should my proxy getter return in this situation? Is it a good idea to return the proxy itself, or a promise to itself?
Example is here:
What is confusing to me is that if I await
an object, I get the object, but if I await
a Proxy
, it needs to have a 'then' property trap which returns itself.
Upvotes: 5
Views: 2474
Reputation: 282
You might consider returning undefined
or an object without a then
method, because await calls then
recursively until the resolved object has no more then
method.
Take this example:
(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);
})();
It just returns "Result: { then: undefined }
, because we return self
in (...args: any[]) => self
which would be replaced with your own logic of course.
If you replace the target { then: undefined }
with something else like { test: "abc" }
there will be no result at all, because the promise becomes never fulfilled and console.log will never be called at all.
So as a conclusion, no - I would not recommend returning the proxy object itself in the then
method.
Upvotes: 3