Node.js Q promises, why use defer () when you can use this ()?

I wanted to do something like:

somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

This did not work. I could not get it to work. I was recommended to use defer() for this purpose.

Their own documents say that we should use deferred functions for callback functions. Although this is confusing because their famous smoothing pyramid example is all callbacks, but the example is too abstract to follow.

Therefore, I see a lot of people using defer , and this is what I did:

 somePromiseFunc(value1) .then(function(value2) { var promise = q.defer(); funcWithCallback(function(err, dronesYouAreLookingFor){ if (!err) promise.resolve(dronesYouAreLookingFor); else promise.reject(new Error(err)); }); return promise.promise; }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

Until I found out about the source code, this also works:

 somePromiseFunc(value1) .then(function(value2) { return function() { funcWithCallback(arguments[1]); }; }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

Why shouldn't I use this much simpler undocumented version?

It is undocumented because, although it seems to smooth the pyramid, return function(){withCB(arguments[1])} works, and return function(err, cb){withCB(cb)} does not work.

+6
source share
1 answer

This is not a legitimate way to use the promise library. As stated in the promises specification that Q aims to fulfill, everything you return from a .then callback, which is not a promise, must have passed through.

In essence, callback-based code should be considered legacy when using promises.

You have two main options. If you use funcWithCallback many times, you can do something like:

 var promisedFunc = Q.nfbind(funcWithCallback); somePromiseFunc(value1) .then(function(value2) { return promisedFunc(); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

or if you need to pass arguments:

 var promisedFunc = Q.nfbind(funcWithCallback); somePromiseFunc(value1) .then(function(value2) { return promisedFunc(value1, value2); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

If you use it only after you can do

 somePromiseFunc(value1) .then(function(value2) { return Q.nfcall(funcWithCallback); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 

or if you need to pass arguments:

 somePromiseFunc(value1) .then(function(value2) { return Q.nfcall(funcWithCallback, value1, value2); }) .then(function(dronesYouAreLookingFor){ // Have a party }) .done(); 
+9
source

All Articles