Skip to content

Instantly share code, notes, and snippets.

@hsubra89
Last active August 29, 2015 14:04
Show Gist options
  • Save hsubra89/9aaa5af19ef2e245c4d7 to your computer and use it in GitHub Desktop.
Save hsubra89/9aaa5af19ef2e245c4d7 to your computer and use it in GitHub Desktop.
callback vs promise basic example
function a(text) {
console.log(text);
}
/********************************* Callback style ****************************/
setTimeout(function() {
var text = "Hello World";
// Calling the next function using its reference // cb style
a(text);
// call next function in the chain
}, 2000);
/********************************* Promise style *****************************/
var q = require('q'); // External package
// delayed function
function delay() {
var d = q.defer();
setTimeout(function() {
var text = "Hello World";
return d.resolve(text);
}, 2000);
return d.promise;
}
// Calling deferred style
delay()
.then(function(text) {
return a(text);
})
.then(....) // next function in the chain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment