Javascript 在三元运算符中使用单个 await

Javascript use single await in ternary operator

我有一种情况想在三元运算符中使用 await 。我想根据条件将值设置为文字值或承诺的解析值。希望下面的代码能帮助描述我想做的事情,但我很确定它是不正确的,所以考虑它是伪代码。

const val = checkCondition ? "literal value" : await promiseGetValue();

其中 promiseGetValue() returns 解析为文字值的承诺。正确的做法是什么?

这实际上是一个有效的语法,为清楚起见,您可以用方括号括起 await promiseGetValue()。这是此语法的演示。

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

你可以使用这个语法, 但是,您应该始终在 async 函数中使用 await 。 您可以 return 您正在等待的函数中的任何值(它不一定是承诺,但在不是 returning 承诺的函数上使用 await 没有意义)

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

条件运算符需要 表达式 作为操作数,并且 await value 是一个有效的表达式。

因此,如果在异步函数内部或在支持顶层 await 的模块的顶层使用(其中 await 有效),您的代码是完全有效的。

对此我无话可说。

基于:你写的方式非常好,但你也可以这样做:

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

也就是说,将整个三元表达式,用括号括起来,加上await。如果没有括号,您将只是 await true.

使用带有三元运算符的 await 只要函数带有 async 关键字就有效。

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