Last active
August 29, 2015 14:22
-
-
Save giuscri/7a3932ba38e3834dbc66 to your computer and use it in GitHub Desktop.
Homemade http wrapper.
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
(function () { | |
"use strict"; | |
/** | |
* Use case example: | |
* http.get("/", {foo: "bar", background: "red"}) | |
* .then(function (res) { | |
* return console.log(res); | |
* }, function (err) { | |
* return console.error(err); | |
* }); | |
**/ | |
var http = {}; | |
http.util = {}; | |
http.util.encodeParameters = function (parameters) { | |
var encodedKeyValues = []; | |
for (var key in parameters) { | |
encodedKeyValues.push([key, parameters[key]].join("=")); | |
} | |
var encodedParameters = ""; | |
encodedParameters = encodedKeyValues.join("&"); | |
return encodedParameters; | |
}; | |
http.get = function (url, parameters) { | |
return new Promise(function (fullfill, reject) { | |
var xhr = new XMLHttpRequest(); | |
xhr.addEventListener("error", function () { | |
return reject("Connection error"); | |
}); | |
xhr.addEventListener("progress", function () { | |
return console.log("Loading ..."); | |
}); | |
xhr.addEventListener("load", function () { | |
var self = this; | |
if (self.status != 200) { | |
return reject([self.status, "returned"].join(" ")); | |
} | |
return fullfill(self.responseText); | |
}); | |
url = [url,http.util.encodeParameters(parameters)].join("?"); | |
xhr.open("GET", url, true); | |
xhr.send(); | |
}); | |
}; | |
http.get("/", {foo: "bar"}) | |
.then(function (res) { | |
return console.log(res); | |
}, function (err) { | |
return console.error(err); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment