I'm writing a real-time matching webapp with Node.js, Express & Redis and I need your help.
app.get('/match', function(req, res) {
db.hkeys('testCollection', function(err, keys){
console.log(keys.length + " keys in Redis:");
keys.forEach(function (keyPlayer, i){
db.hget('testCollection', keyPlayer, function(err, obj){
var testObj = JSON.parse(obj);
if ([conditions]){
console.log('--- A match has been found! ---');
console.log('--- Details of match ---');
console.log('ID: ' + keyPlayer);
console.log('Name: ' + testObj.name);
res.render('match', {
match : testObj
});
}
else {
console.log('*** No match has been found ***');
if ((i+1) == keys.length){
console.log('=== No player match found in DB ===');
};
}
});
});
});
});
How can I make this line of code stop when the conditions in the [if] are hit? Is it possible or should I look for a different solution?
db.hget('testCollection', keyPlayer, function(err, obj){
Here's a solution using async:
var async = require('async');
// ...
app.get('/match', function(req, res) {
db.hkeys('testCollection', function(err, keys){
console.log(keys.length + " keys in Redis:");
async.eachSeries(keys, function(keyPlayer, cb) {
db.hget('testCollection', keyPlayer, function(err, obj) {
if (err) return cb(err);
var testObj = JSON.parse(obj);
if ([conditions]){
console.log('--- A match has been found! ---');
console.log('--- Details of match ---');
console.log('ID: ' + keyPlayer);
console.log('Name: ' + testObj.name);
res.render('match', {
match : testObj
});
return cb(true);
}
console.log('*** No match has been found ***');
cb();
});
}, function(err) {
if (!err)
console.log('=== No player match found in DB ===');
if (err && err !== true)
console.log('Error: ' + err);
});
});
});