Created
October 6, 2013 23:10
-
-
Save eugeneware/6860345 to your computer and use it in GitHub Desktop.
How to write code that supports BOTH callbacks and 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'); | |
/** | |
* 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