Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created February 6, 2018 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/4b98baaf63b6f14ac9d9868350464d06 to your computer and use it in GitHub Desktop.
Save JosePedroDias/4b98baaf63b6f14ac9d9868350464d06 to your computer and use it in GitHub Desktop.
ajax promise
function ajax(url, {
method = 'GET',
headers = {},
body = null,
}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
Object.keys(headers).forEach(hn => {
xhr.setRequestHeader(hn, headers[hn]);
});
const cbInner = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
const respHeaders = xhr.getAllResponseHeaders().trim().split('\n').reduce((obj, line) => {
const [key, ...value] = line.split(': ');
return {
...obj,
[key]: value.join(': '),
};
}, {});
resolve({
response: xhr.response,
headers: respHeaders,
});
} else {
reject(xhr);
}
return;
}
};
xhr.onload = cbInner;
xhr.onerror = cbInner;
xhr.send(body);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment