Last active
March 1, 2018 05:19
-
-
Save chrisbuttery/204375cab329d126d521 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 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
👍