Last active
October 7, 2016 05:26
-
-
Save akirattii/bab20a0cfa1ca4bbd2910963209040af to your computer and use it in GitHub Desktop.
ループ内の非同期なfunctionからループ実行のタイミングを制御して、処理全体を同期っぽく動かす方法。 setInterval を使ったループよりも効率的。
This file contains hidden or 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
| // ループ内の非同期なfunctionからループ実行のタイミングを制御して、処理全体を同期っぽく動かす方法。 | |
| // この方法なら setInterval を使ったループよりも効率的。 | |
| var arr = ["a", "b", "c"]; | |
| var iter = function* () { | |
| let i = 0; | |
| let lastIdx = arr.length - 1; | |
| while (true) { | |
| console.log("Before yeild"); | |
| yield funcAsync(arr[i]); // iter.next()が呼ばれるまで停止... | |
| if (i >= lastIdx) { | |
| console.log("Exit!"); | |
| return i; // ループを抜ける | |
| } | |
| i++; | |
| } | |
| }(); | |
| function funcAsync(txt) { | |
| setTimeout(function() { | |
| console.log(`funcAsync: '${txt}' iter.next()を実行...`); | |
| iter.next(); // yeild部分の停止を解除 | |
| }, 2000); | |
| } | |
| // Fire! | |
| iter.next(); | |
| /* | |
| // console log: | |
| Before yeild | |
| funcAsync: 'a' iter.next()を実行... | |
| Before yeild | |
| funcAsync: 'b' iter.next()を実行... | |
| Before yeild | |
| funcAsync: 'c' iter.next()を実行... | |
| Exit! | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment