2

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?

Gary
  • 13,303
  • 18
  • 49
  • 71
eee
  • 280
  • 4
  • 15
  • 1
    What version of chrome, when I try `var x = (await 1) ? foo() : bar();`, I get a Promise in x as expected. – Paul Jan 04 '18 at 04:12
  • Interesting. When I try your operation I also receive x as a Promise. But without the assignment it returns 1. – eee Jan 04 '18 at 04: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 Jan 04 '18 at 04:32
  • Yes thanks for the correction. I only tried this on Chrome console. – eee Jan 04 '18 at 04:50

3 Answers3

3

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.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • I missed the keyword async on foo and bar when I created the question. Already updated it. Sorry about the confusion. The return of `foo()` is a promise. – eee Jan 04 '18 at 04:12
2

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.

Perhaps this is a only bug of chrome console?

Thanks to Paulpro

eee
  • 280
  • 4
  • 15
  • 1
    The chrome console is breaking standards "under the hood"! The code should throw a syntax error because `await` is only recognised as an operator within an async function. – traktor Jan 04 '18 at 05:12
  • 1
    @traktor53 They added that it a pretty recent release: https://developers.google.com/web/updates/2017/08/devtools-release-notes#await . Note that the REPL doesn't claim to run in the global scope, so it could easily be eval'd within an async function. – Paul Jan 04 '18 at 09:06
0

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

Mahesh
  • 1,427
  • 2
  • 19
  • 42