I tried this with Chrome console:
const foo = async () => 1;
const bar = async () => 2;
(await 1) ? foo() : bar();
The result is 1.
Can you explain this please? Isn't it suppose to return a Promise?
I tried this with Chrome console:
const foo = async () => 1;
const bar = async () => 2;
(await 1) ? foo() : bar();
The result is 1.
Can you explain this please? Isn't it suppose to return a Promise?
await
coerces non-promise operands to a promise by calling Promise.resolve(operand)
. So
(await 1)
becomes
(await Promise.resolve(1))
and Promise.resolve(1)
returns a promise fulfilled with the value 1.
After await returns (asynchronously - after executing a job in the promise job queue*) the ternary expression is evaluated as
1 ? foo() : bar() // calls foo()
The precedence of the await
operator appears to be the same as that of other unary operators.
*Note await
never continues execution in the same call out from the event loop even if the promise it is waiting on is already fulfilled: it always returns in another call out from the event loop.
It seems the chrome console did something under the hood which is not the concern of this question. The result of the operation is as expected.
Thanks to Paulpro
await expects async function as an argument and it halts the operation until the promise in async function is returned. In your case 1 is the expression and hence it is returned immediately. Now your ternary operator takes 1 as an expression which is true in JavaScript's logic. This will trigger your first function i.e. foo So your result will be 1