Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript use single await in ternary operator

I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

const val = checkCondition ? "literal value" : await promiseGetValue();

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?

like image 872
Max888 Avatar asked May 31 '20 19:05

Max888


People also ask

Can I use await in ternary operator?

Using await with ternary operator is valid as long as the function with async keyword.

Can we use only await in promises?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.

Can you await a non async function JavaScript?

You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so.

Is ternary faster than if else?

A ternary operator is a single statement, while an if-else is a block of code. A ternary operator is faster than an if-else block.


1 Answers

The conditional operator expects expressions as operands, and await value is a valid expression.

So, if used inside an async function or in the top-level of a module that supports top-level await (where await is valid), your code is completely valid.

I can't say anything else about that.

like image 51
FZs Avatar answered Sep 17 '22 14:09

FZs