Create a gist now

Instantly share code, notes, and snippets.

Embed
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