Skip to content

Instantly share code, notes, and snippets.

@eugeneware
Created October 6, 2013 23:10
Show Gist options
  • Save eugeneware/6860345 to your computer and use it in GitHub Desktop.
Save eugeneware/6860345 to your computer and use it in GitHub Desktop.
How to write code that supports BOTH callbacks and promises
var Q = require('q');
/**
* Promise functions that take both node callbacks and promises
*/
function half(cb) {
var d = Q.defer();
setImmediate(function() {
d.resolve(21);
})
return d.promise.nodeify(cb);
}
function doubleIt(answer, cb) {
var d = Q.defer();
setImmediate(function() {
d.resolve(answer*2);
})
return d.promise.nodeify(cb);
}
function solve(cb) {
return half()
.then(doubleIt)
.nodeify(cb);
}
/**
* Use the node callback interface to solve()
*/
solve(function (err, result) {
if (err) throw err;
console.log('nodeback', result);
});
/**
* Use the promise interface to solve()
*/
solve().then(function (answer) {
console.log('promise', answer);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment