我有以下的代码,当用户断开连接。 我想发出与房间名和用户名的信号。
client.get('nickname', function(err, name) {
client.get('room', function(err2, room) {
io.sockets.in(room).emit('disconnect', name);
});
});
我的问题是,有没有办法避免缠绕.get
调用这个样子? 我的应用程序,他们会迅速增加。 我可以得到比从一个一个的值更多get()
命令? 还是我处理这一切错了吗?
如果你需要得到很多的价值观,看看像一个流量控制库异步 。 例如,下面是你可能会get
来自客户端几个值并行 :
var async = require('async');
async.parallel([
client.get.bind(this, 'nickname'),
client.get.bind(this, 'room'),
client.get.bind(this, 'anotherValue')
], function(err, results) {
// here, `err` is any error returned from any of the three calls to `get`,
// and results is an array:
// results[0] is the value of 'nickname',
// results[1] is the value of 'room',
// results[2] is the value of 'anotherValue'
});
如果你有一个对象/数组的一个用户的所有属性,并在对象/数组房间的所有属性,你仍然只需要这两个嵌套调用。 你这样做是正确的。