Open billie66 opened 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 一起配合,收集返回值
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 中取出了他们的信息。
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);
});
}
]);
比如你有两件事要做,一个是让一些数据入库,第二个是,读取这些数据,那么这个时候 nodejs 直接顺序写两个函数是不行的,因为异步 IO,但是这个确实只是个先后关系而已,所以用 series 最合适了。
http://justinklemm.com/node-js-async-tutorial/
的帮助很大,注意他还有还有 github 的 demo code
异步执行,这样能首先完成上面的两个 function,然后能够收集返回值,很牛。