gpt4 book ai didi

node.js - 在 NodeJS 中发送 HTTP 响应之前等待事件发生?

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:19 25 4
gpt4 key购买 nike

我正在寻找一种在发送 HTTP 响应之前等待事件发生的解决方案。

用例

  1. 我的想法是在我的一条 route 调用一个函数:zwave.connect("/dev/ttyACM5"); 该函数立即返回。
  2. 但是存在 2 个事件通知连接设备是成功还是失败:
zwave.on('driver ready', function(){...});
zwave.on('driver failed', function(){...});
  1. 在我的路由中,我想知道设备在发送 HTTP 响应之前是连接成功还是失败。

我的“解决方案”

  1. 当事件发生时,我将事件保存在数据库中:
zwave.on('driver ready', function(){
//In the database, save the fact the event happened, here it's event "CONNECTED"
});
  1. 在我的 route ,执行连接功能并等待事件发生出现在数据库中:
router.get('/', function(request, response, next) {     
zwave.connect("/dev/ttyACM5");
waitForEvent("CONNECTED", 5, null, function(){
response.redirect(/connected);
});
});

// The function use to wait for the event
waitForEvent: function(eventType, nbCallMax, nbCall, callback){
if(nbCall == null) nbCall = 1;
if(nbCallMax == null) nbCallMax = 1;

// Looking for event to happen (return true if event happened, false otherwise
event = findEventInDataBase(eventType);

if(event){
waitForEvent(eventType, nbCallMax, nbCall, callback);
}else{
setTimeout(waitForEvent(eventType, callback, nbCallMax, (nbCall+1)), 1500);
}
}

我认为这不是一个好的做法,因为它会在数据库上迭代调用。那么您对此有什么意见/建议呢?

最佳答案

我已经继续并添加了 标记您的问题,因为它的核心就是您要问的问题。 (顺便说一句,如果您不使用 ES6,您应该能够将下面的代码转换回 ES5。)

长话短说

在 JavaScript 中有很多方法可以处理异步控制流(另请参阅:What is the best control flow module for node.js?)。您正在寻找一种结构化的方式来处理它——可能是 Promise s 或 Reactive Extensions for JavaScript (a.k.a RxJS) .

使用 Promise 的示例

来自 MDN:

The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.

在您的案例中,异步计算是描述连接到设备的成功或失败的 bool 值的计算。为此,您可以将对 connect 的调用包装在 Promise 对象中,如下所示:

const p = new Promise((resolve) => {
// This assumes that the events are mutually exclusive
zwave.connect('/dev/ttyACM5');
zwave.on('driver ready', () => resolve(true));
zwave.on('driver failed', () => resolve(false));
});

一旦您有了表示连接状态的 Promise,您就可以将函数附加到它的“ future ”值:

// Inside your route file
const p = /* ... */;
router.get('/', function(request, response, next) {
p.then(successful => {
if (successful) {
response.redirect('/connected');
}
else {
response.redirect('/failure');
}
});
});

您可以了解有关 Promises 的更多信息 on MDN ,或阅读有关该主题的许多其他资源之一(例如 You're Missing the Point of Promises)。

关于node.js - 在 NodeJS 中发送 HTTP 响应之前等待事件发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com