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
/** | |
* Check out following URL's | |
* http://www.html5rocks.com/en/tutorials/es6/promises/ | |
* http://www.html5rocks.com/en/tutorials/es6/promises/#toc-async | |
* http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/ | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
* | |
* Try this code out on http://repl.it/ | |
* | |
* At present, promises are not yet supported by all browsers and some javascript libraries | |
* offer this functionality already. | |
* | |
* Q seems to be a popular implementation but it's performance seems not that good | |
* https://github.com/kriskowal/q | |
* | |
* Bleubird seems like the most promising implementation in terms of performance | |
* https://github.com/petkaantonov/bluebird | |
* | |
* I hope to find some time soon to prepare a demo with bluebird. | |
***/ | |
function factorial(n) { | |
return new Promise(function(resolve, reject) { | |
if (n < 0) { | |
reject(new Error("n has to be larger than 0!!")); | |
} else { | |
var result = 1; | |
do { | |
result *= n; | |
n--; | |
} | |
while (n > 1); | |
return resolve(result); | |
} | |
}); | |
} | |
function onSucces(result) { | |
console.log("succesfully calculated " + result); | |
} | |
function onError(error) { | |
console.log(error.toString()); | |
} | |
factorial(5).then(onSucces, onError); | |
//succesfully calculated 120 | |
factorial(-3).then(onSucces, onError); | |
//Error: n has to be larger than 0!! |
No comments:
Post a Comment