在 node.js 中使用函数数组工作正常,但 await 不等待?

Using array of functions in node.js works fine, but the await does not wait?

我正在尝试使用一组函数来根据传入的值执行适当的函数:

const functions = {
  VALUE_1: async function (body, context) {
    await alertEventService.receivedValue1(body, context)
  },
  VALUE_2: async function (body, context) {
    await alertEventService.receivedValue2(body, context)
  },
  VALUE_3: async function (body, context) {
    await alertEventService.receivedValue3(body, context)
  },
  VALUE_4: async function (body, context) {
    await alertEventService.receivedValue4(body, context)
  },
}

我是这样调用函数的:

router.post('/system/', auth.required, async function (req, res) {
      try {
        let response_def = await functions[`${req.body.event_type}`](req.body, req.context) // This await does not seem to wait! 
        if (response_def) {
          res.status(response_def)
        } else {
          res.status(400).send(`Something went wrong with the system message`)
        }
      } catch (error) {
        log.error(error)
        res.status(500).send(error)
      }
})

问题是当到达 if 语句时 response_def 总是未定义,因此即使请求成功,代码总是 returns 状态 400。

我已经仔细检查了被调用函数中的所有代码,一切都已正确线程化。

除了没有等待,一切正常。我从被调用函数返回 204。

如有任何想法,我们将不胜感激。我不想用开关!

response_def 未定义,因为您 return 什么都没有。

你应该这样写

const functions = {
  VALUE_1: async function (body, context) {
    return await alertEventService.receivedValue1(body, context)
  },
  VALUE_2: async function (body, context) {
    return await alertEventService.receivedValue2(body, context)
  },
  VALUE_3: async function (body, context) {
    return await alertEventService.receivedValue3(body, context)
  },
  VALUE_4: async function (body, context) {
    return await alertEventService.receivedValue4(body, context)
  },
}

请注意,最后一个 await 不是必需的,async 也不是必需的,这也应该有效,但不太明确

const functions = {
  VALUE_1(body, context) {
    return alertEventService.receivedValue1(body, context)
  },
  VALUE_2(body, context) {
    return alertEventService.receivedValue2(body, context)
  },
  VALUE_3(body, context) {
    return alertEventService.receivedValue3(body, context)
  },
  VALUE_4(body, context) {
    return alertEventService.receivedValue4(body, context)
  },
}