admin管理员组

文章数量:1183188

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?

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?

Share Improve this question asked May 31, 2020 at 19:29 Max888Max888 3,7404 gold badges34 silver badges76 bronze badges 2
  • see this post: medium.com/@griffinmichl/… – Denis Stukalov Commented May 31, 2020 at 19:32
  • What exactly is the problem you need help with? Your code looks valid to me. – jfriend00 Commented May 31, 2020 at 20:24
Add a comment  | 

5 Answers 5

Reset to default 12

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

本文标签: Javascript use single await in ternary operatorStack Overflow