gpt4 book ai didi

node.js - 处理 socket.io 异步获取/设置调用

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:48 24 4
gpt4 key购买 nike

我正在尝试询问房间中的任何客户是否拥有与其关联的特定属性。 socket.io get 方法的异步性质给我带来了问题。我看过 async库,看起来它可能是我需要的,但我很难想象如何将它应用到这种情况。

这是我希望该函数如何工作,假设 get 不是异步的;

/**
*
**/
socket.on('disconnect', function(data) {
socket.get('room', function(err, room) {
if(!roomHasProperty(room)) {
io.sockets.in(room).emit('status', { message: 'property-disconnect' });
}
});
});

/**
*
**/
var roomClients = function(room) {
var _clients = io.sockets.clients(room);
return _clients;
}

/**
*
**/
var roomHasProperty = function(room) {
// get a list of clients in the room
var _clients = roomClients(room);
// build up an array of tasks to be completed
var tasks = [];
// loop through each socket in the room
for(key in _clients) {
var _socket = _clients[key];
// grab the type from the sockets data store and check for a control type
_socket.get('type', function (err, type) {
// ah crap, you already went ahead without me!?
if(type == 'property') {
// found a the property type we were looking for
return true;
}
});
}
// didn't find a control type
return false;
}

有更好的方法吗?

最佳答案

您是否考虑过使用 promises 库?它使处理异步函数变得容易得多。如果您要使用 Q ,你可以这样做:(很抱歉,我现在无法检查代码,但我很确定它几乎可以在没有任何更改的情况下工作)

var roomHasProperty = function(room) {
// Create the deferred object
var deferred = Q.defer();
// get a list of clients in the room
var _clients = roomClients(room);
// array of promises to check
var promises = [];

// This function will be used to ask each client for the property
var checkClientProperty = function (client) {
var deferred = Q.defer();
// grab the type from the sockets data store and check for a control type
client.get('type', function (err, type) {
// ah crap, you already went ahead without me!?
if(type == 'property') {
// found a the property type we were looking for
deferred.resolve(true);
} else {
// property wasn't found
deferred.resolve(false);
}
});
return deferred.promise;
}
// loop through each socket in the room
for(key in _clients) {
promises.push(checkClientProperty(_clients[key]));
}
Q.all(promises).then(function (results) {
deferred.resolve(results.indexOf(true) > -1);
})
// didn't find a control type
return deferred.promise;
}

你可以这样使用:

checkClientProperty(client).then(function (result) {
if (result) {
console.dir('the property was found');
} else {
console.dir('the property was not found');
}
});

关于node.js - 处理 socket.io 异步获取/设置调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16460175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com