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?
Using await with ternary operator is valid as long as the function with async keyword.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With