0

I am making a simple app using socket.io and node.js and I have started to think about access to array from different events. So when somebody is joining to room I am pushing him to an array of all clients. Then I am looking for a specific client in an array to change some of his attributes. Finally when client disconnects I am removing him from array. Is there a chance that after function finds index of a specific client that client disconnects and the wrong client attribute will be changed? Here is piece of code

let array=[];

io.on('connection', function (client) {
  client.on('join',function(data){
    array.push(client);
  });
  client.on('message',function(data){
    let index= findOtherClientIndexInArray();
    if(index>-1){
        //If client leaves the array is altered so the index is not pointing at correct client
        array[index].attribute++;
    }
  });
  client.on('leave',function(data){
    array.splice(array.indexOf(client),1)
  });
});
1
  • What do you mean by "wrong client attribute will be changed"? Are you asking if a wrong client could be removed? Node.js being single-threaded should take care of what you're worried about either way, I belive. Commented Aug 29, 2018 at 14:36

1 Answer 1

1

No, there is no risk of index no longer referring to the intended client in the array within a block of synchronous code, since Node.js is a single-threaded environment.

However, if I could make a suggestion for improving your maintainability a little, you could use a Set instead of an array:

let set = new Set();

io.on('connection', function (client) {
  client.on('join', function (data) {
    set.add(client);
  });

  client.on('message', function (data) {
    // return client directly instead of a key or index
    // return undefined or null if none is found
    let other = findOtherClientInSet();

    if (other) {
      other.attribute++;
    }
  });

  client.on('leave', function (data) {
    set.delete(client);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer and for suggesting using sets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.