I haven't worked with ZeroMQ but from the docs I assume that on
seems to be an event subscription mechanism, and not a NodeJS-style asynchronous operation accepting callback. It may fire more than once, right?
If this is the case, why do you want to use promises at all? They seem like the wrong abstraction for this particular situation.
Promises represent operations that finish or fail once, not asynchronous streams of values.
Even if
var requestFrontend = frontendOn('message').then(function(){
console.log("Message received");
});
worked, it wouldn't be of any benefit to you because then
would only be called once.
I assume that's not what you wanted.
If you're looking for a way to filter, map, merge or throttle asynchronous sequences, you can look into RxJS which does exactly that (it also interfaces with promises). But promises shouldn't, and can't be used as substitute for events that fire more than once.
On the other hand, if the message really does come only once, I agree it's best to use promises to abstract it away. However, nfbind
or nbind
won't work here because they require function(err, result)
-style callbacks, and you have function(result)
.
Here's what I suggest you use instead:
function promiseOneMessage(queue) {
var deferred = Q.defer();
queue.on('message', deferred.resolve);
queue.on('error', deferred.reject);
return deferred.promise;
}
var requestFrontend = promiseOneMessage(frontend)
.then(function (message) {
console.log("Message received", message);
})
.done();
var requestBackend = promiseOneMessage(backend)
.then(responseBackend)
.done();