在第一场比赛中停止Redis

时间:2014-09-16 11:31:24

标签: javascript node.js redis

我正在使用Node.js,Express& amp;编写实时匹配的webapp。 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){

1 个答案:

答案 0 :(得分:0)

以下是使用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);
    });
  });
});