1月15日開催!現年収非公開で企業からスカウトをもらってみませんか?PR

転職ドラフトでリアルな市場価値を測る。レジュメをもとに、企業から年収とミッションが提示されます。

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 3 years have 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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address