在第一场比赛中停止Redis hget

Stop a Redis hget on first match

本文关键字:hget Redis 一场      更新时间:2023-09-26

我正在用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);
    });
  });
});