LoginSignup
0
1

More than 3 years have passed since last update.

Promise.all と mapで重い並列処理を実装する

Posted at

状況

firebaseなどからデータが多数入っている配列をとってきたとき、
それらの配列の要素一つ一つに重い処理を非同期でやっていきたい

解決策

sample.ts
const data = await db.collection('test').get()
//data一つ一つに対して、重い処理をしていきたい
const promises = data.map(async (item) => {
  await sampleFunction1(item)
  await sampleFunction2(item)
}
Promise.all(promises)

配列data をmapを用いて、一つ一つの要素に処理をしていく。
そんで、それら処理したやつをpromises(type of array) に代入。
promisesには、処理済みの配列dataが入っている。

それらの配列を Promise.allで並列処理したらok

その他

配列の処理には、

for (const item of data ) {}
data.forEach((item) => {})

などfor文を使う手法もあるが、
中で、await を使うような重い処理を使う場合は、処理済み配列を代入できるmapPromise.allを使った方が断然楽。

0
1
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
0
1