微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

异步方法作为三元表达式中的表达式

如何解决异步方法作为三元表达式中的表达式

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

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

解决方法

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

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

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

,

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


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);
,

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?