23
23

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 5 years have passed since last update.

Promiseを直列で実行する

Last updated at Posted at 2014-07-12

並列で実行したい場合は Promise.all([promise...]) すれば事足りるんだけど、直列で実行しようとするとちょっとややこしい。

# 実行すると1秒後に実行回数をprintするPromise化された関数
cnt = 0
f = -> new Promise (done) ->
  setTimeout (->
    console.log 'done', cnt++
    done()
  ), 1000

# fを直列に4回実行する
promises = [f, f, f, f]
seq = promises.reduce ((ret, p) ->
  ret.then p
), promises.shift()()

seq.then => console.log 'finish'

実行結果

done 0
done 1
done 2
done 3
finish 

Array.prototype.reduceでthenを繋ぐのが肝

23
23
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
23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?