Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created June 12, 2017 21:47
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 kentbrew/07490e5989964d886541c9f7c5833f89 to your computer and use it in GitHub Desktop.
Save kentbrew/07490e5989964d886541c9f7c5833f89 to your computer and use it in GitHub Desktop.
XHR + Promises + responseType
var xhr = o => {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
o.method = o.method || 'GET';
// third parameter must be there and be true to use o.formData
req.open(o.method, o.url, true);
// default text; can send json
req.responseType = o.responseType || 'text';
// get reply back from API in proper language
req.setRequestHeader('Accept-Language', window.navigator.language);
// for writing to DB
if (o.csrfToken) {
req.setRequestHeader('X-CSRFToken', o.csrfToken);
}
// got something
req.onload = () => {
// somewhere in the 200 range is good
if (req.status > 199 && req.status < 300 ) {
resolve(req.response);
}
else {
// status outside the 200 range = error
reject(Error("Status Error " + req.statusText));
}
};
// got nothing
req.onerror = () => {
reject(Error("Network Error " + req.statusText));
};
// are we posting something?
if (o.formData) {
req.send(o.formData);
} else {
req.send();
}
});
}
var file = {
// we know this should work, since Pinterest widgets have CORS
good_xhr_widget_reply_json: {
url: 'https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=99360735500167749',
responseType: 'json'
},
good_xhr_cors_reply_html: {
url: 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html'
},
// XHR Access-Control-Allow-Origin fail
bad_xhr_github_cors: {
url: 'https://github.com'
},
// 404 not found
bad_xhr_name_not_resolved: {
url: 'http://githuuuuuub.com'
},
// 404 not found
bad_xhr_github_cors_and_404: {
url: 'http://github.com/splootius-maxiumus'
}
};
// where our results will go
var win = {};
var fail = {};
// when we're all done, show results
var done = () => {
console.log('WIN', win);
console.log('FAIL', fail);
};
// file counter
var toGo = 0;
// are we there yet?
var checkDoneLoading = () => {
toGo = toGo - 1;
if (!toGo) {
done();
}
};
// request all files
for (let k in file) {
toGo = toGo + 1;
xhr(file[k]).then(
// worked
response => {
win[k] = response;
checkDoneLoading();
},
// failed
error => {
fail[k] = error;
checkDoneLoading();
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment