Search code examples
javascriptasync-awaites6-promiseconditional-operator

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

  • 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()