Last active
May 27, 2016 17:34
-
-
Save Gerrit0/94ddc589f31cd87e068ae6e16c8ee5d9 to your computer and use it in GitHub Desktop.
A micro ajax helper for promises
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
let ajax = (function() { | |
/** | |
* Easily make an XHR request. | |
* | |
* @param {string} protocol | |
* @param {string} url | |
* @param {object} params -- WARNING. Only accepts shallow objects. | |
* @return {Promise} | |
*/ | |
function xhr(protocol, url = '/', params = {}, headers = {}) { | |
var paramStr = Object.keys(params) | |
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) | |
.join('&'); | |
return new Promise(function(resolve, reject) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(protocol, url); | |
if (protocol == 'POST') { | |
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
} | |
Object.keys(headers).forEach(key => { | |
xhr.setRequestHeader(key, headers[key]); | |
}); | |
xhr.onload = function() { | |
if (xhr.status == 200) { | |
resolve(xhr.response); | |
} else { | |
reject(Error(xhr.statusText)); | |
} | |
}; | |
// Network error, or rejected connection | |
xhr.onerror = function() { | |
reject(Error("Network Error")); | |
}; | |
if (paramStr) { | |
xhr.send(paramStr); | |
} else { | |
xhr.send(); | |
} | |
}); | |
} | |
/** | |
* Function to GET a page. Passes the response of the XHR in the resolve promise. | |
* | |
* @param {string} url | |
* @param {object} params | |
* @param {object} headers | |
* @return {Promise} | |
*/ | |
function get(url = '/', params = {}, headers = {}) { | |
return xhr('GET', url, params, headers); | |
} | |
/** | |
* Function to make a post xhruest | |
* | |
* @param {string} url | |
* @param {object} params | |
* @param {objct} headers | |
* @return {Promise} | |
*/ | |
function post(url = '/', params = {}, headers = {}) { | |
return xhr('POST', url, params, headers); | |
} | |
return {xhr, get, post}; | |
}()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment