Skip to content

Instantly share code, notes, and snippets.

@jondlm
Created September 22, 2014 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jondlm/b95d2c1eaaade7b2c115 to your computer and use it in GitHub Desktop.
Save jondlm/b95d2c1eaaade7b2c115 to your computer and use it in GitHub Desktop.
Node style callbacks to q promises
var Q = require('q');
var assert = require('assert');
// Node style callback
function echo(thing, callback) {
callback(null, thing + thing);
}
//
// Test code
// -------------------------------------
// Standard node version
echo('hello', function(err, result) {
assert.strictEqual(result, 'hellohello');
console.log('good');
});
// Using the `call` promise approach
Q.nfcall(echo, 'there').then(function(result) {
assert.strictEqual(result, 'therethere');
console.log('good');
}).fail(function(err) {
console.log(err);
});
// Creating a reusable promise wrapper
var echoPromised = Q.denodeify(echo);
echoPromised('sir').then(function(result) {
assert.strictEqual(result, 'sirsir');
console.log('good');
}).fail(function(err) {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment