Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Control the flow of asynchronous calls with ES6 generator functions
/**
* get - XHR Request
*/
let get = function (url) {
return function (callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
let response = xhr.responseText;
if(xhr.readyState != 4) return;
if (xhr.status === 200) {
callback(null, response);
}
else {
callback(response, null);
}
};
xhr.send();
};
};
/**
* getTweets (Generator)
*/
let getTweets = function* () {
let totalTweets = [];
let data;
// get the 1st tweet
data = yield get('https://api.myjson.com/bins/2qjdn');
totalTweets.push(data);
// now get the 2nd tweet
data = yield get('https://api.myjson.com/bins/3zjqz');
totalTweets.push(data);
// then get the 3rd tweet
data = yield get('https://api.myjson.com/bins/29e3f');
totalTweets.push(data);
console.log(totalTweets);
}
/**
* runGenerator
* A function that takes a generator function and
* recusively calls next() until `done: true`
*/
let runGenerator = function (fn) {
let next = function (err, arg) {
if (err) return it.throw(err);
var result = it.next(arg);
if (result.done) return;
if (typeof result.value == 'function') {
result.value(next);
}
else {
next(null, result.value);
}
}
let it = fn();
return next();
}
// kick it off
runGenerator(getTweets);

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment