forEach内でpromiseによる逐次処理
すべてブロッキングしながら逐次処理を行う。(コマンドスクリプト用)
参考:http://www.html5rocks.com/en/tutorials/es6/promises/#toc-parallelism-sequencing
var vals = ['hello', 'nice', 'bye'] var sequence = Promise.resolve() vals.forEach(function (currVal) { sequence = sequence .then(function () { return currVal }) .then(init) .then(m1) .then(m2) }) function init (val) { return new Promise((resolve, reject) => { console.log('init:', val) resolve(val) }) } function m1 (val) { return new Promise((resolve, reject) => { setTimeout(function () { console.log('m1:', val) resolve(val) }, 300) }) } function m2 (val) { return new Promise((resolve, reject) => { setTimeout(function () { console.log('m2:', val) resolve(val) }, 100) }) }
結果
init: hello m1: hello m2: hello init: nice m1: nice m2: nice init: bye m1: bye m2: bye