问题陈述: 考虑使用Express库运行REST通讯的Node js程序。 有多个REST API调用,并且所有API都使用一个阻塞资源,该资源一次只能运行一个请求,例如串行端口。
我遇到这样的情况,我收到多个对API调用的并行请求,这些请求又将串行端口用于某些目的。
我如何引导来自不同方法的API调用,然后精简它,然后一个接一个地执行,然后将响应返回给相应的请求?
代码段:
/**
* This function is a blocking function that utilizes the serial port
*/
function request_response(shield, channel, parameter, parameterValue) {
var promise = new Promise(function (resolve, reject) {
var commandString = modbusRTURequestGenerator.modbusRTURequestGenerator(shield, channel, parameter, data, parameterValue);
serialOUT(commandString).then(() => {
Promise.race([serialIN(), timeOut()]).then(results => {
resolve(results);
});
});
});
return promise;
}
/**
* This is a GET Request API to get the parameter values.
*/
router.get("/getParameter", function (req, res) {
var shield = req.query.shield;
var channel = req.query.channel;
var parameter = req.query.parameter;
request_response(shield, channel, parameter, undefined).then(
(result) => {
res.send(result);
});
});
/**
* This is a POST Request API to set the parameter values.
*/
router.post("/setParameter", function (req, res) {
var shield = req.query.shield;
var channel = req.query.channel;
var parameter = req.query.parameter;
var parameterValue = req.body.value;
request_response(shield, channel, parameter, parameterValue).then(
(result) => {
res.send(result);
});
});
/**
* This is a GET Request API for Scan functionality.
*/
router.get("/scan", function (req, res) {
var msg = {};
var cmds_arr = [];
for (var i = 1; i <= constants.NUMBER_OF_SHIELDS; i++) {
cmds_arr.push(i + "," + constants.SCAN_COMMAND_REGISTER);
}
asyncLoop(cmds_arr, function (item, next) {
var params = item.split(",");
var shield = params[0];
var register = params[1];
request_response(shield, undefined, register, undefined).then(
(result) => {
msg[data] = result;
next();
}
});
}, function () {
res.send(msg);
});
});
HTTP REST API有3种:scan,getParameter和setParameter。所有这三个都在访问request_response函数。因此,当我运行扫描API并并行触发getParameter API时,我得到了错误的结果。