简体   繁体   中英

async.series and javascript variables

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM