Last active
August 29, 2015 13:56
-
-
Save raorao/8946698 to your computer and use it in GitHub Desktop.
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
//JavaScript Promises! They are the next big thing in JavaScript, the coolest thing | |
//you've never heard about in the coolest language out there. And as of last year, | |
//They are supported by new builds of Chrome. It's only a matter of time until | |
//they're supported everywhere. So...what are they? | |
//Well, in essence, a Promise represents an asynchronous task. While the task is | |
//being completed, it is represented by a Promise object, and once completed it | |
//returns the value you expected. They are a tool to handle asynchronous functionality | |
//in JavaScript, as well as make your code more readable, extendable, and better at | |
//handling errors. So what do they look like? Well before we can do that, we need to | |
//learn how to make an asynchronous request in JavaScript. Here's an AJAX request in | |
//vanilla JavaScript. | |
function printAPIcall() { | |
var request = new XMLHttpRequest(); | |
request.open('GET','https://api.github.com/zen',true); | |
request.send(); | |
//creates a new request object, provides with the correct url | |
//and then sends that request to the external server. in this case, | |
//we're querying the GitHub testing API, which just returns random quotes. | |
request.onload = function() { console.log( request.response ); }; | |
//adds listener to request, which will only fire once its completed the | |
//request-response cycle. Remember, this is asynchronous! request.response | |
//doesn't exist until the github API actually responds. | |
} | |
printAPIcall() | |
//prints 'Practicality beats purity' to the console. | |
//So now that we can do that, let's learn how to implement this as a Promise. | |
//The first function looks very similar to the one above, except that we've | |
//abstracted out the callback function that executes on completion of the request. | |
//This would be difficult, but not impossible, to do without Promises. | |
var makeAPIcall = function(resolve) { | |
var request = new XMLHttpRequest(); | |
request.open('GET','https://api.github.com/zen',true); | |
request.send(); | |
request.onload = function() { resolve( request.response ) } | |
//instead of writing the logic for what happens once the request has loaded | |
//like we did above, its been defined by a passed-in callback. | |
} | |
//This is a simple function that outputs an uppercase version of its input. | |
//We're going to pass this to makeAPIcall to approximate what we had above | |
var yellResponse = function(words) { | |
console.log( words.toUpperCase() ) | |
} | |
var pinkySwear = new Promise(makeAPIcall) | |
//This creates a basic promise. pinkySwear is a Promise object that takes | |
//a function as an argument. The function will remain unexecuted and the object | |
//will remain a promise object until you tell it what to do with its response. | |
//To do so, you just need to call it with then .then() function, which takes | |
//another callback as an argument. | |
pinkySwear.then(yellResponse) | |
//prints "MIND YOUR WORDS, THEY ARE IMPORTANT." to the console. | |
//Alone, a promise is little more than synactic sugar for asynchronous functions. | |
//But if you have multiple asynchronous calls, you can chain promises to make | |
//your code readable. In this example, validateInputWithAPI and saveInputOnServer would | |
//return new promises. UpdateDOM will actually then, you know, update the DOM. | |
var userLoginFlow = new Promise(getUserInput) | |
userLoginFlow.then(validateInputWithAPI).then(saveInputOnServer).then(updateDOM) | |
//That was awesome! and readable! and didn't require a series of functions-in-functions! | |
//Promises are also great for error handling, since the function passed to the | |
//Promise construction can take a second optional argument corresponding to | |
//a callback that fires on an error. Or really whenever you want, since you write | |
//the control flow entirely by hand. But the multiple callback options are a | |
//great way to manage and bubble errors through your asynchronous code. | |
//I've only touched on the surface of what Promises are capable of. If you want to learn | |
//more, check out this blog post by Bryan Klimt of Parse: | |
//(http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/) | |
//as well as documentation from MDN: | |
//(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | |
//and this great writeup by Sandeep Panda of sitepoint: | |
//(http://www.sitepoint.com/overview-javascript-promises/) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment