我正在使用 Node.js、Express 和 Redis 编写一个实时匹配的网络应用程序,我需要你的帮助。
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 ===');
};
}
});
});
});
});
当满足 [if] 中的条件时,如何让这行代码停止?有可能还是我应该寻找不同的解决方案?
db.hget('testCollection', keyPlayer, function(err, obj){
最佳答案
这是一个使用 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);
});
});
});
关于javascript - 在第一场比赛中停止 Redis hget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25867633/