-
-
Save jondlm/b95d2c1eaaade7b2c115 to your computer and use it in GitHub Desktop.
Node style callbacks to q promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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