Reputation: 1495
I have this function which is getting called once:
exports.validate = function(roomData, callback) {
console.log('This only prints only once!');
getAllRooms(function(rooms) {
if (rooms.length === 0) {
callback(true);
return;
}
for (let i = 0; i < rooms.length; i++) {
let key = "roomAdmin:" + rooms[i].roomName;
redis.hgetall(key, function() {
let newUrl = roomData.url.toLowerCase();
let existingUrl = rooms[i].url.toLowerCase();
let newRoomName = roomData.roomName.toLowerCase();
let existingRoomName = rooms[i].roomName.toLowerCase();
if (newUrl === existingUrl || newRoomName === existingRoomName) {
console.log('This prints');
callback(false);
return;
}
if (i === rooms.length - 1) {
console.log('But this prints also?');
callback(true);
return;
}
})
}
});
};
I am trying to loop through a set of redis objects and compare some fields to some give new data. If there is a match I want to callback with a false and return. If there is no match I want to return true.
I can see my logic is wrong below as hgetall is async so both returns get called, so how do I stop execution and return as soon as I find a match?
Thanks
Upvotes: 0
Views: 60
Reputation: 2187
Stopping execution is on responsibility of hgetall
function, so you can use simplest straightforward solution - pass to it array function, which calls your local let-assigned function. After match is found (Or error occurred), just replace local function to empty. Modern ES interpreter optimizers would execute code fast enough, but additional callbacks will not performed.
Something like following:
let cbc = function() {
let newUrl = roomData.url.toLowerCase();
let existingUrl = rooms[i].url.toLowerCase();
let newRoomName = roomData.roomName.toLowerCase();
let existingRoomName = rooms[i].roomName.toLowerCase();
// ......
if(found) {
cbc = () => {};
callback(result);
return
}
}
// ......
redis.hgetall(key, (...args) => cbc(...args));
Upvotes: 1