Created
August 18, 2014 05:01
-
-
Save hsubra89/5e91b55aa99cfaac4d8a to your computer and use it in GitHub Desktop.
Converting Callback style code to 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'); | |
// Sample Async Function | |
function asyncFunction(data, cb) { | |
setTimeout(function() { | |
// call cb with error | |
cb(new Error('Error')); | |
// Or call with success | |
cb(null, {status: 'true'}); | |
}, 100); | |
} | |
// Converting Async fn to promises | |
// Q has an inbuilt function that does this called q.nfcall | |
// so the following function is the equivalent of : | |
// var promiseFunction = q.nfcall(asyncFunction, data); | |
function promiseFunction(data) { | |
var d = q.defer(); | |
asyncFunction(data, function(err, res) { | |
if(err) d.reject(err); | |
else d.resolve(res); | |
}); | |
return d.promise; | |
} | |
// Now you can call the promise function | |
promiseFunction('hello world') | |
.then(function(data) { | |
// Do some more stuff | |
return status; | |
}) | |
.then(function(data) { | |
// do more stuff | |
}) | |
// the following catch will catch all errors in any .then step before it. | |
.catch(function(err) { | |
// Handle the error here. | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment