user2106769
user2106769

Reputation: 455

await for proxy leads to get of 'then' property, what should I return?

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:

https://jsfiddle.net/rv55Lpu1

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

Answers (1)

Joe
Joe

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

Related Questions