LoginSignup
5
6

More than 5 years have passed since last update.

任意の個数のコールバックつき関数を順番に呼び出す

Last updated at Posted at 2013-09-15

下記のようなコールバックを取る関数を順次呼び出したいとします。

a = (cb) -> setTimeout (-> console.log "a" ; do cb), 300
b = (cb) -> setTimeout (-> console.log "b" ; do cb), 200
c = (cb) -> setTimeout (-> console.log "c" ; do cb), 100 

こういう結果が欲しい。

$ seq. a.coffee
a
b
c

素直なやり方はこう。

a ->
  b ->
    c ->

これだと、個数が固定になっちゃいます。なんとか任意の個数実行できるようにしたい。

そこで、賢いやり方。

_ = require 'underscore'

do _.reduceRight [a, b, c], ((acc, f) -> -> f acc), _.identity

結果はどちらもこうなります。

5
6
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
5
6