javascript - 在第一场比赛中停止 Redis hget

标签 javascript node.js redis

我正在使用 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/

相关文章:

javascript - 如何在javascript中为多维数组赋值?

javascript - 自定义的 Javascript 函数没有像我预期的那样工作?

javascript - 从 Node 使用 mocha js 中的全局窗口变量

html - 提供静态内容目录的快速路由

node.js - 如何在实时添加对象时从 Redis 中弹出对象?

javascript - 使用 AJAX 从 Ruby on Rails 服务器获取 JSON 内容

node.js - 无服务器异步函数错误

docker - 为什么redis不能访问docker-compose中的磁盘?

java - 如何更改 Rails redis 缓存格式?

javascript - 类型错误:generateKeyPairSync 不是函数