Subscribed unsubscribe Subscribe Subscribe

Promiseの配列を順に処理

reduceを使い新しいpromiseを作成していく。

const tasks = [
  () => $q(resolve => doneAsync(resolve)),
  () => $q(resolve => doneAsync(resolve))
];

function doneAsync(resolve) {
  setTimeout(() => resolve(), 1000);
}

tasks.reduce((promise, task) => {
  return promise.then(task);
}, $q.resolve()) // $q.resolve()で最初のPromiseを生成
.then(() => {
  console.log('done');
});

実行結果を保存するrecord処理を追加。

const tasks = [
  (value) => $q(resolve => doneAsync(resolve, value)),
  (value) => $q(resolve => doneAsync(resolve, value))
];

const record = (results, value) => {
  results.push(value);
  return results;
};

// [] に実行結果を保存する
const _record = record.bind(null, []);

tasks.reduce((promise, task) => { 
  return promise.then(task).then(_record)
}, $q.resolve(0))
.then(value => {
  console.log(value);
  // -> [1, 2]
});

function doneAsync(resolve, value) {
  setTimeout(() => resolve(++value), 1000);
}