Created
July 22, 2013 10:26
-
-
Save kazuho/6052876 to your computer and use it in GitHub Desktop.
JavaScript の yield で非同期なコードを動機っぽく書く例
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
// 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