What is the difference between these two async ternary statements?

Viewed 39

Can someone help me understand the difference if any between these two below ternary statements?

const variables = await (conditional ? asyncFunctionOne() : asyncFunctionTwo());
    
const variables = conditional ? await asyncFunctionOne() : await asyncFunctionTwo();

At first glance, these both do the same thing, but some part of me thinks these do not execute in the same order.

1 Answers

There would be a small difference if this were a function call:

const variables = doSomething(conditional ? functionOne() : functionTwo());
    
const variables = conditional ? doSomething(functionOne()) : doSomething(asyncFunctionTwo());

const temp = conditional ? functionOne() : asyncFunctionTwo();
const variables = doSomething(temp);

These may look equivalent on a first glance, but are not if the code in conditional or even inside functionOne/functionTwo does change the doSomething variable.

However, await is not a function but syntax, its meaning is determined when parsing and compiling the code, not when evaluating it and resolving a variable. So the two lines in your question are absolutely equivalent.

Related