5

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.

user3840170
  • 26,597
  • 4
  • 30
  • 62
user2106769
  • 445
  • 5
  • 15
  • the example you tried?or any sample proxy object to try? – zabusa Jan 19 '18 at 10:22
  • Your question is lacking any detail, example, for anyone to really help. Try creating a simple snippet for people to see the issue you mention. – Keith Jan 19 '18 at 10:26
  • example is here https://jsfiddle.net/rv55Lpu1/ What is confusing to me is that if I await an object, i got object, but if the object is simulated by proxy, it needs to have 'then' property trap which return itself. – user2106769 Jan 19 '18 at 10:37
  • its just return the value.you are not returning any promise here – zabusa Jan 19 '18 at 11:12

1 Answers1

2

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.

Joe
  • 272
  • 2
  • 9