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?
Solution 1:
This is actually a valid syntax, just for clarity u can surround the await promiseGetValue() with brackets. here is a demo of this syntax.
const returnPromise = () => Promise.resolve('world')
const f = async () => {
const x = true ? 'hello' : await returnPromise()
const y = false ? 'hello' : await returnPromise()
console.log(x,y)
}
f()
Solution 2:
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.