Created
February 6, 2018 17:26
-
-
Save JosePedroDias/4b98baaf63b6f14ac9d9868350464d06 to your computer and use it in GitHub Desktop.
ajax promise
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
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