2013-05-09 3 views
3

방에있는 클라이언트 중 특정 클라이언트와 연결된 특정 속성이 있는지 질문하는 중입니다. socket.io get 메서드의 비동기 특성으로 인해 문제가 발생합니다. 나는 내가 필요로하는 것처럼 보이는 async 라이브러리를 보았습니다. 그러나이 상황에 적용하는 방법을 시각화하는 데 어려움을 겪고 있습니다.socket.io async get/set 호출 다루기

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; 
} 

더 좋은 방법이 있나요?

+0

비동기 문제 외에도 콜백에서는 true를 반환하고 부모 메서드에서는 true를 반환하는 것으로 나타났습니다. 바보. –

답변

0

약속 라이브러리를 사용 해본 적이 있습니까? 비동기 함수를 훨씬 쉽게 처리 할 수 ​​있습니다. 당신이 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'); 
    } 
});