Async Javascript with Promises

I’ve been struggling with understanding promises for a while but I found this video by Kyle Young really clear and helpful! I definitely recommend it to anyone also trying to better grasp the idea.

After watching the video, it made this article a lot easier to digest:

This code from the above article sets up a nice Promise Pattern on the XMLHttpRequest

function get(url) { * // Return a new promise.* return new Promise(function(resolve, reject) { * // Set up an XHR Object* var req = new XMLHttpRequest();'GET', url); req.onload = function() { * // This is called even on 404 etc* if (req.status == 200) { * // Resolve the promise with the response text* resolve(req.response); } else { * // Otherwise reject with the status text* reject(Error(req.statusText)); } }; * // Handle network errors* req.onerror = function() { reject(Error("Network Error")); }; * // Make the request* req.send(); }); }

This allows the XHR to be used in a really neat promise pattern:

get('story.json') .then(function(response) { console.log("Success!", response); }) .catch(function(error) { console.log("Failed!", error); });

Duncan Leung

Front End Developer at

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!