Javascript use single await in ternary operator

Viewed 5946

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?

5 Answers

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

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.

you can use this syntax, However you should always use await inside async function. You can return any value from function you are awaiting for(its not necessary to be promise, but it doesn't make sense to use await on function which is not returning promise)

function promiseGetValue() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('any value')
        })
    })
}
const flag = false
async function main() {
    const val = flag ? "literal value" : await promiseGetValue();
    console.log(val)
}
main()

Building on ehab's answer: The way you wrote it is perfectly fine, but you can also do it like this:

const returnPromise = () => Promise.resolve("world");
const f = async () => {
  const x = await (true ? returnPromise() : returnPromise());
  console.log(x);
};
f();

That is to say, prepend the entire ternary expression, surrounded by parentheses, with await. Without the parentheses you would just await true.

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

  function promiseFunc() {
      return Promise.resolve({ some: 'data' });
    }
    
    async function myFunc(condition) {
      return condition ? await promiseFunc() : null;
    }
    
    (async () => {
      console.log(await myFunc(true))   // { some: 'data' }
    })()

Related