简体   繁体   English

async.series和javascript变量

[英]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. console.log“test”似乎没有打印,我尝试了很多不同的代码迭代,但是一旦它超出了内部循环(users.push用户),我就不能检索用户的值。 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. 另外,根据您使用的users ,您可能希望使用async.map而不是async.each来简化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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