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

Async method as an expression in ternary expression

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

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 的更多信息,请参阅以下 link。 https://developer.mozilla.org/en-US/docs/Glossary/IIFE

@zishone引用的答案是基于IIFE(Immediately Invoked Function Expression)