Question

I think there's a fundamental disconnect in my understanding. I've been reading up on callbacks and I've searched for why the following might not work, but I may be looking in the wrong places. I have the following code:

  users = []
  async.series [
    () ->
      userClient.smembers "users", (err, list) ->
        async.each list, (item, cb) ->
          userClient.hgetall item, (err, user) ->
            users.push user
        , (err) ->
          console.log err            
    , 
    () -> 
      console.log "test"
      console.log users
    ]

The console.log "test" doesn't seem to be printing, and I've tried a lot of different iterations of the code, but once it gets outside of the inner most loop (users.push user), I can't retrieve the value for users. I end up with an empty array []. Anyone have any insight or can perhaps point out where I've gone wrong in my thinking? Thank you.

Was it helpful?

Solution

Since each function is asynchronous, it cannot know automatically when to progress to the next step in the series. Each series function take a callback as an argument that you need to call.

(doneCallback) ->
  userClient.smembers "users", (err, list) ->
    async.each list, (item, cb) ->
      userClient.hgetall item, (err, user) ->
        users.push user

        // You also need to call 'cb' here.
        cb();
    , (err) ->
      console.log err

      // Add this to go to the next step after.
      doneCallback(err)

Also depepending on what you are using users for, you may want to use async.map instead of async.each to simplify the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top