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()
})();
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.
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.
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.
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.
It's actually happening twice.
Why is
.then()
triggered on a Proxy returned by anasync 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With