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?
Share Improve this question edited Jan 6, 2018 at 20:35 Gary 13.9k18 gold badges53 silver badges72 bronze badges asked Jan 4, 2018 at 3:47 eeeeee 2804 silver badges15 bronze badges 4-
1
What version of chrome, when I try
var x = (await 1) ? foo() : bar();
, I get a Promise in x as expected. – Paul Commented Jan 4, 2018 at 4:12 - Interesting. When I try your operation I also receive x as a Promise. But without the assignment it returns 1. – eee Commented Jan 4, 2018 at 4:24
-
I see what the question is now (it's not reproducible from your original code without adding semicolons), since it is interpreted as
(async () => 2)(await 1)
without a semicolon after the 2, unless it is entered line by line. – Paul Commented Jan 4, 2018 at 4:32 - Yes thanks for the correction. I only tried this on Chrome console. – eee Commented Jan 4, 2018 at 4:50
3 Answers
Reset to default 3await
coerces non-promise operands to a promise by calling Promise.resolve(operand)
. So
(await 1)
bees
(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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745392520a4625726.html
评论列表(0条)