在node.js中使用函数数组工作得很好,但是await不等待?



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

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

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

我仔细检查了被调用函数中的所有代码,所有代码都是正确的。

除了不等待,一切都很好。我从被调用的函数返回一个204。

任何想法都将非常感激。我不想用开关!

response_def未定义,因为您没有返回任何内容。

你应该这样写

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

相关内容

  • 没有找到相关文章

最新更新