Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
})();
like image 695
millsp Avatar asked Jan 18 '18 10:01

millsp


People also ask

Why does await return a promise?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What does await do in async function?

The await expression is usually used to unwrap promises by passing a Promise as the expression . This causes async function execution to pause until the promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.

Why use async await vs then?

Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then() , the rest of the function will continue to execute but JavaScript won't execute the . then() callback until the promise settles.

Do you need to use await when calling an async function?

If you forget to use await while calling an async function, the function starts executing. This means that await is not required for executing the function. The async function will return a promise, which you can use later.


1 Answers

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.

like image 135
Bergi Avatar answered Oct 07 '22 00:10

Bergi