Skip to content

Instantly share code, notes, and snippets.

@kazuho
Created July 22, 2013 10:26
Show Gist options
  • Save kazuho/6052876 to your computer and use it in GitHub Desktop.
Save kazuho/6052876 to your computer and use it in GitHub Desktop.
JavaScript の yield で非同期なコードを動機っぽく書く例
// based on http://labs.cybozu.co.jp/blog/kazuho/archives/2007/05/coopthread.php
function get_all(urls) {
runnable(function (next) {
for (var i = 0; i < urls.length; i++) {
// build request
var xhr = new XMLHttpRequest();
xhr.open("get", urls[i], true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4)
next(xhr.responseText);
};
xhr.send(null);
// handle response
var responseText = yield;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment