【问题标题】:Javascript use single await in ternary operatorJavascript 在三元运算符中使用单个等待
【发布时间】:2020-09-19 02:48:57
【问题描述】:

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

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

promiseGetValue() 返回一个解析为文字值的承诺。这样做的正确方法是什么?

【问题讨论】:

标签: javascript async-await es6-promise conditional-operator


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    ehab's answer 为基础:您编写它的方式非常好,但您也可以这样做:

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

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

    【讨论】:

      【解决方案3】:

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

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

      对此我无话可说。

      【讨论】:

        【解决方案4】:

        你可以使用这个语法, 但是,您应该始终在 async 函数中使用 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()

        【讨论】:

        • 完全没有解释性文字的答案总是可以通过添加解释您试图提出的观点的文字来改进和完善。
        • 感谢您的建议
        • 另外,当我尝试在 sn-p 中运行您的代码时,它没有运行,因为未定义 checkCondition
        【解决方案5】:

        这实际上是一个有效的语法,为了清楚起见,你可以用括号括住 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()

        【讨论】:

          猜你喜欢
          • 2021-07-14
          • 2019-10-08
          • 1970-01-01
          • 2020-04-29
          • 1970-01-01
          • 2010-12-11
          • 2013-11-14
          • 2012-07-25
          • 2013-01-23
          相关资源
          最近更新 更多