javascript - Operator precedence between await and ternary - Stack Overflow

I tried this with Chrome console:const foo = async () => 1;const bar = async () => 2;(await 1)

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
Add a ment  | 

3 Answers 3

Reset to default 3

await 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信