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 data; | |
let totalTweets = []; | |
// 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); | |
} | |
// initialise iterator | |
let it = getTweets(); | |
// kick it off | |
let result = it.next(); | |
result.value(function(err, res){ | |
if (err) console.log('do something with this error', err); | |
// get the response and pass it in as a param to be saved | |
let result = it.next(res); | |
result.value(function(err, res){ | |
if (err) console.log('do something with this error', err); | |
// get the response and pass it in as a param to be saved | |
let result = it.next(res); | |
result.value(function(err, res){ | |
if (err) console.log('do something with this error', err); | |
// get the response and pass it in as a param to be saved | |
let result = it.next(res); | |
}) | |
}); | |
}); | |
// ^ Remind you of anything? Gross right?! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment