Created
February 26, 2017 04:04
-
-
Save Xom/e27ab0b98a2a12f1bf479c6b8751a402 to your computer and use it in GitHub Desktop.
XMLHttpRequest wrapped in ES6 Promise
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
// https://github.com/mdn/js-examples/blob/master/promises-test/index.html | |
xhr = function(url, responseType) { | |
return new Promise(function(resolve, reject) { | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.responseType = responseType; | |
request.onload = function() { | |
if (request.status === 200) { | |
resolve(request.response); | |
} else { | |
reject(Error(`${url} failed to load; error code: ${request.statusText}`)); | |
} | |
}; | |
request.onerror = function() { | |
reject(Error(`${url} failed to load; there was a network error.`)); | |
}; | |
request.send(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment