Created
March 9, 2015 10:28
-
-
Save stopsatgreen/691a361be4953e132eda to your computer and use it in GitHub Desktop.
XHR with Promises
This file contains hidden or 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
// Create new Promise | |
function get(url) { | |
return new Promise(function(resolve, reject) { | |
var req = new XMLHttpRequest(); | |
req.open('GET', url); | |
req.onload = function() { | |
if (req.status == 200) { | |
resolve(req.response); | |
} else { | |
reject(Error(req.statusText)); | |
} | |
}; | |
req.onerror = function() { | |
reject(Error("Network Error")); | |
}; | |
req.send(); | |
}); | |
} | |
// Then call it | |
get(reqURL).then(function (response) { | |
console.log(response); | |
}, function(error) { | |
console.error('Failed!', error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment