I'm unable to reproduce what you're seeing. Running your code under a couple of different conditions, I got the following results:
> var lobbies = [{ lobbyName: 'foo' }];
> doesLobbyExist('foo', console.log)
foo exists!
true
> doesLobbyExist('bar', console.log)
...
> var lobbies = [{ lobbyName: 'foo' }, { lobbyName: 'bar' }, { lobbyName: 'foo' }];
> doesLobbyExist('bar', console.log)
bar exists!
true
> doesLobbyExist('foo', console.log)
foo exists!
true
foo exists!
true
...
> var lobbies = [];
> doesLobbyExist('foo', console.log)
false
but there a couple of problems in your code:
lobbyExists
only gives a false
response if there are no lobbies to check, it's possible for it to call the callback multiple times if there are multiple lobbies with the same name, and it doesn't return anything if a lobby isn't found.
- there's no easy way to break out of
forEach
. since you only want to call your callback function once, you'll want to either return
or break
once a lobby has been found. switching over to a for i
loop allows us to do either one.
- comparison using == is what's known as loose or abstract equality, which may cause errors down the road - you can read up on the difference between loose (==) and strict (===) equality here.
- if the
lobbyExists
function is only iterating through an array, then there's no need to treat it as asynchronous and use a callback. synchronous callbacks are a thing, and are perfectly fine to use, but it's something to be aware of as you continue to develop.
with all that being said, these are the changes that I would suggest:
function doesLobbyExist(a, callback) {
lobbyExists(a, function(random_data) {
//possibly do other things to random_data...
callback(random_data);
});
}
function lobbyExists(a, callback) {
for(var i = 0; i < lobbies.length; i++) {
var l = lobbies[i];
if(l.lobbyName === a) {
console.log(a + " exists!");
callback(true);
return;
}
}
callback(false);
}