Skip to content

Instantly share code, notes, and snippets.

@ChrisBuchholz
Last active December 23, 2016 10:06
Show Gist options
  • Save ChrisBuchholz/7871204 to your computer and use it in GitHub Desktop.
Save ChrisBuchholz/7871204 to your computer and use it in GitHub Desktop.
var init = sync(function* (resume) {
var data1, data2;
console.log('Start by waiting for a second...');
yield sleep(1000, resume);
console.log('Then send a GET request to a couple of websites with XMLHttpRequest');
data1 = yield get('https://cors-test.appspot.com/test', resume);
data2 = yield get('https://cors-test.appspot.com/test', resume);
console.log(data1);
console.log(data2);
});
init();
<!doctype html>
<meta charset=utf-8 />
<script src="lib.js"></script>
<script src="app.js"></script>
var sync = function (generator) {
return function() {
var iterator, resume;
resume = function() {
if (!arguments[0]) iterator.next(arguments[1]);
else iterator.throw(arguments[0]);
};
iterator = generator(resume);
iterator.next();
};
};
var get = function(url, resume) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200)
resume(null, xhr.responseText);
else
resume('Failed to fetch ' + url);
}
};
xhr.send(null);
};
var sleep = function(ms, resume) {
setTimeout(resume, ms);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment