I am looking for a solution to wait for an event before sending an HTTP response.
Use case
- The idea is that I call a function on one of my routes:
zwave.connect("/dev/ttyACM5");This function returns immediately. - But there are 2 events that indicate that they will succeed or fail to connect the device:
zwave.on('driver ready', function(){...});
zwave.on('driver failed', function(){...});
- In my route, I would like to know if the device was successful or failed to connect before sending an HTTP response.
My decision"
- When an event occurs, I save the event in the database:
zwave.on('driver ready', function(){
});
- In my route, execute the connection function and wait for the event in the database:
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);
}
}
, , .
, / ?