Created
June 8, 2016 04:49
-
-
Save hisasann/254ddefbcfadc7a920a35fc448d46036 to your computer and use it in GitHub Desktop.
generator と yield を使った async / await パターン
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
import 'babel-regenerator-runtime'; | |
var aa = (this && this.aa) || require('async-await'); | |
var Promise = aa.Promise; // native Promiseがあれば不要 | |
console.log('main: start'); | |
aa(main()).then(function (val) { | |
console.log('main: finish:', val); | |
}); | |
function *main() { | |
var result; | |
console.log('main: started'); | |
// シーケンシャル処理(逐次処理) | |
result = yield sleep(200, 'a1'); | |
console.log('main-a1: sleep: a1 =', result); | |
result = yield sleep(100, 'a2'); | |
console.log('main-a2: sleep: a2 =', result); | |
result = yield sleep(300, 'a3'); | |
console.log('main-a3: sleep: a3 =', result); | |
// パラレル処理(並行処理) ... 配列やオブジェクトで結果を取得 | |
result = yield [sleep(200, 'b1'), sleep(100, 'b2'), sleep(300, 'b3')]; | |
console.log('main-b : parallel Array :', result); | |
return 'return value!'; | |
} | |
function sleep(msec, val) { | |
return new Promise(function (resolve, reject) { | |
// setTimeout の第三引数で resolve の引数に val を渡している | |
setTimeout(resolve, msec, val); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment