Created
July 18, 2018 20:34
-
-
Save gabemeola/72d278418fd89ff070103ac1cf73aa03 to your computer and use it in GitHub Desktop.
Fetch for old browsers
This file contains hidden or 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
| /** | |
| * Small request wrapper for XMLHttpRequest | |
| * with an API similar to fetch. | |
| * | |
| * @author Gabe M. | |
| * @param {string} url - Resource Url for Request | |
| * @param {Object} config | |
| * @param {string} [config.method=GET] - REST request method | |
| */ | |
| function request(url, { method = 'GET' } = {}) { | |
| return new Promise((resolve, reject) => { | |
| const req = new XMLHttpRequest(); | |
| req.onload = () => { | |
| if (req.status >= 200 && req.status < 300) { | |
| resolve({ | |
| status: req.status, | |
| statusText: req.statusText, | |
| text: () => Promise.resolve(req.responseText), | |
| json: () => | |
| Promise.resolve(req.responseText).then(JSON.parse), | |
| }); | |
| } else { | |
| reject(new Error(req.statusText)); | |
| } | |
| }; | |
| req.onerror = reject; | |
| req.open(method, url, true); | |
| req.send(); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment