Created
January 24, 2015 02:21
-
-
Save chrisbuttery/9fcef92ae783a8ed74c8 to your computer and use it in GitHub Desktop.
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
// Thunk | |
let get = function (url) { | |
// return a function, passing in our callback | |
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(); | |
}; | |
}; | |
let getTweets = function* () { | |
let totalTweets = []; | |
let data; | |
// pause and get the 1st tweet. Continue when next() is called | |
data = yield get('https://api.myjson.com/bins/2qjdn'); | |
totalTweets.push(data); | |
// pause and get the 2nd tweet. Continue when next() is called | |
data = yield get('https://api.myjson.com/bins/3zjqz'); | |
totalTweets.push(data); | |
// then get the 3rd tweet. Continue when next() is called | |
data = yield get('https://api.myjson.com/bins/29e3f'); | |
totalTweets.push(data); | |
return totalTweets; | |
}; | |
var cb = function(err, res) { | |
if (err) return console.error(err); | |
console.log(res); | |
}; | |
// iterator object | |
let iterator = getTweets(); | |
iterator.next().value(cb); | |
iterator.next().value(cb); | |
iterator.next().value(cb); | |
iterator.next(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment