【问题标题】:Async method as an expression in ternary expression异步方法作为三元表达式中的表达式
【发布时间】:2021-07-10 11:49:13
【问题描述】:

我试图在三元表达式中调用异步方法作为条件,但代码的执行没有按预期工作。 有人可以向我解释为什么会这样:

req.user.user_id === concept.owner_id
  ? async () => {
      console.log("here");
      const update = req.body;
      update.concept_id = conceptId;
      update.owner_id = concept.owner_id;
      const updatedConcept = await Concept.updateConcept(update);
      updatedConcept !== null
        ? ResponseSuccess.success(res, updatedConcept)
        : ResponseError.internalServerError(res);
    }
  : ResponseError.unauthorized(res);

不工作? 我验证了条件为真。仅供参考 ResponseSuccessResponseError 只是响应处理程序和格式化程序。 是不是因为两个部分是不同的类型?

TIA

【问题讨论】:

  • 我没有看到你在任何地方调用 async 函数。所以我看到的是,当条件为真时,三元表达式将评估为函数定义。
  • 是的,刚刚注意到。谢谢@crashmstr

标签: node.js async-await conditional-operator


【解决方案1】:

您必须使用 IIFE 才能在声明时调用函数。有关 IIFE 的更多信息,请参阅以下链接。 https://developer.mozilla.org/en-US/docs/Glossary/IIFE

@zishone 引用的答案是基于IIFE(立即调用函数表达式)

【讨论】:

    【解决方案2】:

    你不是在调用异步函数,你只是在分配它。

    
    req.user.user_id === concept.owner_id
      ? (async () => {
          console.log("here");
          const update = req.body;
          update.concept_id = conceptId;
          update.owner_id = concept.owner_id;
          const updatedConcept = await Concept.updateConcept(update);
          updatedConcept !== null
            ? ResponseSuccess.success(res, updatedConcept)
            : ResponseError.internalServerError(res);
        })()                                              // Do this to call it
      : ResponseError.unauthorized(res);
    

    【讨论】:

      【解决方案3】:

      您实际上并没有在三元运算符的真正方面执行您的函数。你需要这样的东西

        await (req.user.user_id === concept.owner_id
          ? async () { ... }
          : async () {
            return ResponseError.unauthorized(res)
        )()
      

      但我强烈建议您为此使用 if 语句。

      【讨论】:

      • 为什么偏爱“if语句”而不是三元表达式?
      • 阅读 if 语句比阅读三元运算符中的内联函数要容易得多。此外,您不必将 false 部分包装在另一个内联函数中。
      猜你喜欢
      • 1970-01-01
      • 2017-12-24
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2015-07-13
      • 1970-01-01
      相关资源
      最近更新 更多