Created
March 5, 2019 13:43
-
-
Save romaricpascal/09015901cfb48f216bee18cdd0343c45 to your computer and use it in GitHub Desktop.
Get a Promise out of an XHR
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 send( | |
url, | |
{ method = 'GET', data, headers = {}, user, password, ...opts } = {} | |
) { | |
const xhr = new XMLHttpRequest(); | |
const promise = new Promise((resolve, reject) => { | |
xhr.open(method, url, true, user, password); | |
xhr.addEventListener('load', resolve); | |
xhr.addEventListener('error', reject); | |
xhr.addEventListener('abort', reject); | |
xhr.addEventListener('timeout', reject); | |
Object.entries(headers).forEach(([name, value]) => | |
xhr.setRequestHeader(name, value) | |
); | |
Object.entries(opts).forEach(([name, value]) => { | |
xhr[name] = value; | |
}); | |
xhr.send(data); | |
}); | |
// Expose the xhr to allow abortion and listening to other events | |
promise.xhr = xhr; | |
return promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably seeing this too late, but you can use the
method
argument of the function to pick which HTTP method to use when sending the request :)