1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.js デザインパターン Promise 逐次イテレーション

Posted at

Node.jsで、Promiseを使用したイテレーションのデザインパターンについて学んだので書いていく。

複数の、Promiseオブジェクトを返すタスクを逐次実行するのには、以下のパターンが有効

let tasks = [task1, task2, task3]

let promise = Promise.resolve()

function task1() {
  Promise.resolve(console.log('task1 completed'))
}

function task2() {
  Promise.resolve(console.log('task2 completed'))
}

function task3() {
  Promise.resolve(console.log('task3 completed'))
}

tasks.forEach(task => {
  console.log('task handled')
  promise = promise.then(() => {
    return task()
  })
})

console.log('all tasks handled')

promise.then(() => {
  console.log('all tasks completed!')
})

このコードを実行すると、コンソールは以下の通りになる。

> "task handled"
> "task handled"
> "task handled"
> "all tasks handled"
> "task1 completed"
> "task2 completed"
> "task3 completed"
> "all tasks completed!"

このように、配列にタスクを格納し、それをforEachなどで回してpromiseのチェーンを繋いでいくイメージ。
また、forEachの代わりにreduceを用いるとよりコンパクトに書くことができる。↓

let tasks = [task1, task2, task3]

function task1() {
  Promise.resolve(console.log('task1 completed'))
}

function task2() {
  Promise.resolve(console.log('task2 completed'))
}

function task3() {
  Promise.resolve(console.log('task3 completed'))
}

let promise = tasks.reduce((prevPromise, task) => {
  console.log('task handled')
  return prevPromise.then(() => {
    return task()
  })
}, Promise.resolve())

console.log('all tasks handled')

promise.then(() => {
  console.log('all tasks completed!')
})
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?