Reputation: 14954
Please excuse my newbishness with the concept of promises. I'm using the Q module in Node.js. I have a function that is meant to call a callback once it has performed all the necessary steps. The problem occurs when I want to call the callback function from within the Q promise.
My desired functionality is to be able to call the callback when I reach the final step, and no longer be within the chain of promises. Thus, the callback will be back to its original operation. However, as I have coded it, the callback gets called within the context of the promise. At this point, should the callback (say) throw an error, it gets caught by the error handler in this function, which is not what I want!
var updateDataStream = function(data, input, posts, stream, callback) {
// Pack all the items up...
Q.ncall(data._packStream, data, posts, stream)
// Upsert the cache into the database
.then(function(){
return Q.ncall(data.upsert, data);
})
// buffer the new input
.then(function(res){
return Q.ncall(data.buffer, data, input);
})
.then(function(final){
callback(null, final);
})
.fail(function(err){
console.log('OHNOES!!!!!!!',err);
}).end();
}
In this context, an error happening within the callback function causes "OHNOES!!!!!" to be printed....
Upvotes: 6
Views: 979
Reputation: 3846
There is a method, nodeify
that will (optionally) break out of a promise chain and forward to a NodeJS-style continuation.
var updateDataStream = function(data, input, posts, stream, callback) {
// Pack all the items up...
return Q.ncall(data._packStream, data, posts, stream)
// Upsert the cache into the database
.then(function(){
return Q.ncall(data.upsert, data);
})
// buffer the new input
.then(function(res){
return Q.ncall(data.buffer, data, input);
})
.nodeify(callback);
}
Note the added "return" at the beginning of the chain and the "nodeify(callback)" added at the end.
Your users need be none the wiser that you’re using Q at all…unless they leave off the callback, in which case they will get a promise instead.
Upvotes: 4