Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created June 10, 2016 11:35
Q's Node Resolver Will Aggregate Results In An Array When Necessary
// Require our core node modules.
var chalk = require( "chalk" );
var Q = require( "q" );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
// I invoke the given node-style callback with ONE result.
function withOneResults( callback ) {
callback( null, "A" );
}
// I invoke the given node-style callback with TWO results.
function withTwoResults( callback ) {
callback( null, "A", "B" );
}
// I invoke the given node-style callback with THREE results.
function withThreeResults( callback ) {
callback( null, "A", "B", "C" );
}
// For each method above, we're going to use Q's .makeNodeResolver() method. The number
// of results passed to resolver influences the type of data that the resolver passed
// down the promise chain.
[ withOneResults, withTwoResults, withThreeResults ].forEach(
function tryMethod( method ) {
var deferred = Q.defer();
// Q's .makeNodeResolver() will automatically resolve or reject the promise
// based on what it is passed to it (assuming a node-style callback signature).
method( deferred.makeNodeResolver() );
deferred.promise.then(
function handleResolve( results ) {
console.log( chalk.red( method.name + ":" ), results );
return( results );
}
);
// NOTE: We could have also just used "Q.nfcall( method )", which would have
// given us the same outcome. But, using the .makeNodeResolver() directly makes
// the demo a bit more explicit.
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment