Last active
August 29, 2015 14:04
-
-
Save hsubra89/9aaa5af19ef2e245c4d7 to your computer and use it in GitHub Desktop.
callback vs promise basic example
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
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