John
John

Reputation: 1276

how to handle implicit return in coffeescript when using async.js

i'm trying to get

testFunction: () ->
  console.log "testFunction"
  async.series(
    (->
      console.log "first"
    ),
    (-> 
      console.log "second"
    )
  )

i've also tried to no success

testFunction: () ->
  console.log "testFunction"
  async.series(
    (->
      console.log "first"
      return undefined
    ),
    (-> 
      console.log "second"
      return undefined
    )
  )

to run, i would expect console output of "testFunction", "first", "second" but I'm getting "testFunction", "second" and it seems like there is a problem with coffeescript's use of implicit returns, (I guess).

Attached is a screen shot of the javascript output compiled from the above coffeescript.

enter image description here

Upvotes: 1

Views: 977

Answers (2)

Aaron Dufour
Aaron Dufour

Reputation: 17505

You've got a number of problems. The first is that you're not passing the correct arguments to async.series. It expects:

async.series([functions...], callback)

while you're calling

async.series(function, function)

Since the length attribute of the first function is undefined, it assumes its an empty array and skips straight to the "callback" (second function). It sounds like you may want to pass an array of two functions and omit the callback.

The second problem is that functions passed to async.series must call a callback in order for progression to continue. The callback is the first argument to each function:

testFunction: () ->
  console.log "testFunction"
  async.series([
    ((next) ->
      console.log "first"
      next()
    ),
    ((next) -> 
      console.log "second"
      next()
    )
  ])

async ignores the return value of most (all?) functions that you pass to it.

Upvotes: 3

Peter Lyons
Peter Lyons

Reputation: 145994

Every function that does work for async needs to take a callback as its only argument.

one = (callback) ->
  console.log "one"
  callback()

two = (callback) ->
  console.log "two"
  callback()

testFunction: () ->
  console.log "testFunction"
  async.series [one, two], (error) ->
    console.log "all done", error

Upvotes: 4

Related Questions