Conclusion from Q promise in Node.js when making a callback?

Please excuse my newbie with the concept of promises. I am using the Q module in Node.js. I have a function that is designed to call a callback after completing all the necessary steps. The problem occurs when I want to call a callback function from a Q promise.

My desired functionality is to be able to call a callback when I get to the last step and will no longer be in the promises chain. Thus, the callback will return to the original operation. However, as I encoded it, the callback is called in the context of the promise. At this point, if the callback (say) throws an error, it falls into the error handler in this function, which I donโ€™t 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 that occurs in the callback function calls "OHNOES !!!!!" for print....

+6
source share
1 answer

There is a nodeify method that (optionally) breaks from the promise chain and proceeds to continue the NodeJS style.

 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 should not be wiser that you use Q at all ... unless they leave a callback, in which case they will receive a promise instead.

+4
source

Source: https://habr.com/ru/post/921536/


All Articles