Skip to content

Instantly share code, notes, and snippets.

@hsubra89
Created August 18, 2014 05:01
Show Gist options
  • Save hsubra89/5e91b55aa99cfaac4d8a to your computer and use it in GitHub Desktop.
Save hsubra89/5e91b55aa99cfaac4d8a to your computer and use it in GitHub Desktop.
Converting Callback style code to promises
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