Skip to content

Instantly share code, notes, and snippets.

@hisasann
Created June 8, 2016 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hisasann/254ddefbcfadc7a920a35fc448d46036 to your computer and use it in GitHub Desktop.
Save hisasann/254ddefbcfadc7a920a35fc448d46036 to your computer and use it in GitHub Desktop.
generator と yield を使った async / await パターン
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