1

It continues execution even if the condition is true and return res.json() is executed.

_.each(rooms, function(room){
    if(room.users.length == users.length) {
        return res.json(room); // <-- returns but still continuous execution
    }
});

Below is the error printed in console.

error: Error: Cannot write to response more than once

Do I need to do anything else?

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Sahil Deliwala
  • 802
  • 1
  • 7
  • 14

3 Answers3

0

you should break the loop and then res.status(200).json(room)

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
0

As posted in How to break/exit from a each() function in JQuery?, you can exit each loops by returning false. Thus,

_.each(rooms, function(room){
    if(room.users.length == users.length) {
        res.json(room);
        return false;
    }
});

If that did not work and you used underscore.js, see how to break the _.each function in underscore.js which recommends using .every where return false works (instead of .each). Thus

_.every(rooms, function(room){
    if(room.users.length == users.length) {
        res.json(room);
        return false;
    }
});
Community
  • 1
  • 1
serv-inc
  • 35,772
  • 9
  • 166
  • 188
0

You could consider using a different function in the underscore/lodash api, for example, find would seem to suit what you are doing better:

var room = _.find(rooms, function(room){
  return room.users.length == users.length;
});
res.json(room);
BrettJephson
  • 416
  • 5
  • 13