Search code examples
javascriptecmascript-6babeljses6-promisees6-proxy

Why does 'await' trigger '.then()' on a Proxy returned by an 'async' function ?


I am compiling the code with babel (env), compiling down to ES5.

Here's the code:

(async () => {
     const p = async () => {
          return new Proxy({}, {
               get: (target, property) => {
                    console.log(property);
               }
          })
     };

     const r = await p();// await calls .then on the result of p()
})();


Solution

  • It's actually happening twice.

    Why is .then() triggered on a Proxy returned by an async function?

    The result of an async function call is a promise that is resolved with the return value from the function body evaluation. Resolving a promise checks whether the resolution value is a thenable ("promise-like value"), which would lead to the promise waiting for the inner result. (In your case, accessing .then on the proxy does not return a function, so it's not considered a thenable and the promise is fulfilled with the proxy).

    Why does await trigger .then() on a Proxy?

    Same here. await does not work only with promises, it works on arbitrary values. To determine their "promise-worthiness", it runs exactly the same thenable check - it resolves a promise with the awaited value and then waits for the promise to settle.