Last active
March 20, 2017 10:47
-
-
Save chrisbuttery/7bbd291b3a69b2e60787 to your computer and use it in GitHub Desktop.
Control the flow of asynchronous calls with ES6 generator functions
This file contains 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
/** | |
* 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