@thex I have reviewed your code and have a few changes to suggest (see revised code below).
- For error cases, i.e. ‘not the right event’, you should reject the promise. This way you can handle the failed promise later on (see next point)
- To handle failed promises you should use .catch() as shown below. The code will call .catch() if the timeout occurs (raises an TimeoutError) or if ‘not the right event’ Error is raised. For the latter you can define your own Error class.
One side note. Plugins for pimatic shall be written using Coffeescript. This may be a bit of a hurdle in the beginning, but also has lot of benefits once you are familiar with it.
var Promise = require('bluebird');
var EventEmitter = require("events").EventEmitter;
var ee = new EventEmitter();
ee.on("someEvent", function (id) {
console.log("event " + id + " has occured");
});
setTimeout(function emitEvent() {
ee.emit("someEvent", 1);
},
1000
);
setTimeout(function emitEvent() {
ee.emit("someEvent", 2);
},
2000
);
setTimeout(function emitEvent() {
ee.emit("someEvent", 3);
},
3000
);
function waitForEvent(id) {
var def = Promise.pending();
ee.once('someEvent', function (eventId) {
if (id == eventId) {
//the right event has happened
console.log('right event');
def.resolve();
}
else {
//not the right event, keep waiting
console.log('not the right event');
def.reject(new Error('not the right event'));
}
});
return def.promise;
}
var waitingPromise = waitForEvent(2).timeout(5000, 'timed out').then(
function () {
console.log('promise fulfilled because of right event');
}).catch(function (err) {
console.log('promise failed:' + err);
});
console.log('waiting...');
EDIT: The code should work as is. I have doe some test runs at least
. Regarding the use of the timeout() see also https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms–string-message—promise
EDIT2: I didn’t pay enough attention to your first as you wrote you want the Promise to be only be “fulfilled if an UDP answer has been received and is matching the request”. If you want handle multiple send/receive activities at the same time it does not make sense to reject the Promise if the wrong event has been received as replies may be in a different order than sent requests. For this case simply remove the “def.reject” code line for the code above. This way the Promise will be rejected only if the expected reply to a given request has not been received with the given timeout period.
"It always takes longer than you expect, even when you take into account Hofstadter's Law.", Hofstadter's Law