Created
June 8, 2016 04:50
-
-
Save hisasann/acd203ef760e898e9be2bc802c0f42dd to your computer and use it in GitHub Desktop.
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
'use strict'; | |
import 'babel-regenerator-runtime'; | |
// require('babel-polyfill'); // おまじない | |
//require('regenerator').runtime(); | |
console.log('main: start'); | |
main().then(function (val) { | |
console.log('main: finish:', val); | |
}); | |
async function main() { | |
var result; | |
console.log('main: started'); | |
// シーケンシャル処理(逐次処理) | |
result = await sleep(1000, 'a1'); | |
console.log('main-a1: sleep: a1 =', result); | |
result = await sleep(500, 'a2'); | |
console.log('main-a2: sleep: a2 =', result); | |
// パラレル処理(並行処理) | |
result = await Promise.all([sleep(200, 'b1'), sleep(100, 'b2'), sleep(300, 'b3')]); | |
console.log('main-b : Promise.all([promises]): [b1, b2, b3] =', result); | |
return 'return value!'; | |
} | |
function sleep(msec, val) { | |
return new Promise(function (resolve, reject) { | |
setTimeout(resolve, msec, val); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment