Last active
March 9, 2017 23:28
-
-
Save jsonberry/8b91105030b37e3e460e1a70dd584489 to your computer and use it in GitHub Desktop.
Simple Asynchronous JavaScript Promise 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
// TODO | |
// Add Promise.race example | |
// Add Promise.all example | |
// Refactor async simulations to better reflect real-world scenarios | |
// Refactor so that if the evenOrOdd async work is not wrapped in a Promise that it could cause unexpected behavior sometimes depending on JS Type/Reference errors | |
function getRandomData() { | |
return { | |
number: Math.floor(Math.random() * 10), | |
timeout: Math.floor(Math.random() * 10000) | |
} | |
} | |
function evenOrOdd(data) { | |
return new Promise(function(resolve, reject) { // Wrapping reponse in Promise to ensure explicit Promise behavior regardless of data | |
setTimeout(function() { // Simulate another async request in the Promise then chain | |
if (!(data.number % 2)) { | |
resolve(`The count was even, I resolved with: [${data.number}] it took ${data.timeout + 1000} milliseconds`); | |
} | |
else { | |
reject(`The count was odd, I resolved with: ${data.number} it took ${data.timeout + 1000} milliseconds`); | |
} | |
}, data.timeout); | |
}); | |
} | |
function onFulfilled(data) { | |
console.log('onFulfilled Called'); | |
console.log('.......do fulfilling things.......') | |
console.log(data); | |
} | |
function onRejected(reason) { | |
console.log('onRejected Called'); | |
console.log('Rejected reason:', reason); | |
console.log('.......do error handling things.......') | |
} | |
var asyncRequest = new Promise (function(resolve, reject) { | |
setTimeout(function() { // Simulating asynchronous event like an AJAX call | |
resolve(getRandomData()); | |
}, 1000); | |
}); | |
asyncRequest | |
.then(evenOrOdd) | |
.then(onFulfilled) | |
.catch(onRejected); | |
/* Resources | |
https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch3.md#chapter-3-promises | |
http://www.ecma-international.org/ecma-262/6.0/#sec-promise-constructor | |
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment