Last active
August 29, 2015 13:58
-
-
Save hoodwink73/9959677 to your computer and use it in GitHub Desktop.
An abstraction of the general GET method using new Promises in JS
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
// An abstraction of the general GET method using | |
// new Promises in JS | |
var get = function (url) { | |
// returns a promise object | |
return new Promise(function (resolve, reject) { | |
// the callback to the Promise constructor | |
// gets two callbacks as parameters | |
// the first is meant to be invoked for succes | |
// and second one for failures | |
var request = new XMLHTTPRequest(); | |
request.open('GET', url); | |
request.onload = function () { | |
if (request.status === 200) { | |
// invoke the success callback with the response | |
resolve(request.response); | |
} else { | |
// if HTTP status was anything other than success | |
// invoke the failure callback | |
reject(new Error(request.statusText)); | |
} | |
} | |
// Handle network error | |
request.onerror = function () { | |
reject(new Error("Network Error")); | |
} | |
request.send(); | |
}); | |
}; | |
// Here's is how you will use it | |
var resolve = function (response) { | |
console.log("Request was successful", response); | |
}; | |
var reject = function (error) { | |
console.error("Request Failed", error); | |
} | |
get("../dummy_url.json").then(resolve, reject); | |
var getJOSN = function () { | |
// parse the plain text response into JSON | |
// the 'then' method of the promise returns a promise itself | |
get(url).then(JSON.parse); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment