happypeter / classroom

Nodejs+socket.io+Redis + rails 搭建的一个 demo 程序
20 stars 5 forks source link

async.js tips #4

Open billie66 opened 10 years ago

billie66 commented 10 years ago
async.parallel([
    function(callback){
            callback(null, 'one');
            // null is a MUST here
    },
    function(callback){
            callback(null, 'two');
    }
],
// optional callback
function(err, results){
    console.log(results);
    // will output  'one' 'two'
});

异步执行,这样能首先完成上面的两个 function,然后能够收集返回值,很牛。

happypeter commented 10 years ago
function getLoginTime(arrayOfUsername, cb){
  async.parallel([
    function(callback){
       callback(null, 'three');
    },
    function(callback){
       callback(null, 'four');
    }
    ],
    function(err, results){
      cb(results);
    }
  );
}
...
// then I can use it like below

  getLoginTime(arrayOfUsername, function(value){
        io.sockets.emit('user joined', {
          username: socket.username,
          numUsers: numUsers,
          usernames: usernames,
          loginTime: value
        });
   });

aync 和回调函数 cb 一起配合,收集返回值

happypeter commented 10 years ago
function getLoginTime(arrayOfUsername, cb){

  var asyncTasks = [];

  arrayOfUsername.forEach(function(username){
    asyncTasks.push(function(callback){

      redis.get("connect_id:" + username, function(err, key){
        redis.hget("connect:" + key, 'online', function(err, value){
          callback(null, value);
        });
      });

    });
  });

  async.parallel( asyncTasks,
    function(err, results){
      console.log("************lastLoginTimesalldone******"+ results);
      cb(results);
    }
  );
}

这个是上面 commit 中的代码,实现用 parallel 实现了 each 迭代,取出了 array 中所有的 username 并分别去 redis 中取出了他们的信息。

happypeter commented 10 years ago
async.series([
      function(callback){
        redis.incr("connect_id", function(err, id){
           var t = new Date();
           redis.hset("connect:" + id, "online", t.getTime());
           redis.set("connect_id:" + username, id);
           callback(null);
           // if I put callback() out of incr() this won't work
           // so callback() is really the end point of the execution
        });
      },

      function(callback) {
        getLoginTime(arrayOfUsername, function(value){
          io.sockets.emit('user joined', {
            username: socket.username,
            numUsers: numUsers,
            usernames: usernames,
            loginTime: value
          });
          callback(null);
        });
      }
    ]);

series 其实最常用

比如你有两件事要做,一个是让一些数据入库,第二个是,读取这些数据,那么这个时候 nodejs 直接顺序写两个函数是不行的,因为异步 IO,但是这个确实只是个先后关系而已,所以用 series 最合适了。

happypeter commented 10 years ago

http://justinklemm.com/node-js-async-tutorial/

的帮助很大,注意他还有还有 github 的 demo code