2016-10-03 56 views
0

我正试图学习如何在我的节点js REST API中使用异步方法。节点异步方法未检测到迭代器的结果

目标

我查询数据库,以使每一个范围键...和循环。我检查是否有任何结果与我当前的日期/时间戳相匹配,如果有,我对匹配键进行HGETALL查询。 我想将HGETALL的结果作为json数据发送给我的REST API的使用者。

问题

我的代码正确查询后为HGETALL数据库的初始密钥组......然后。 但是,当我尝试发回结果时,网页上当前没有显示任何内容。

下面的代码:

var id_rule = function (redis_key, doneCallBack) { 
    console.log('iterator called with key:' + redis_key); 
    //if this is the default rule, skip it 
    if (redis_key.indexOf('00:00_00:00') == -1){ 
     //time match 
     var rule_times = parse_time_from_key(redis_key); 
     var current = getCurrentUTC(); // returns something like [ 1158, 'mon' ]   
     if ((current[0] >= rule_times[0] && current[0] <= rule_times[1]) && (rule_times[2].indexOf((current[1].substring(0,1))) != -1)) { 
      var widgetkey = redis_key.split("widget:");    
      redis.hgetall("widget:" + widgetkey[1], function (err, data) { 
       if (err) { 
        console.log("hgetall method fails: " + err); 
        return doneCallBack(err, false); 
       } 
       if (data) { 
        console.log('bingo: ' + widgetkey[1] + "returned a match"); 
        console.log(data); 
        return doneCallBack(false, data); 
       } else { 
        return doneCallBack(false, false); 
       }          
      }); 
     } else { 
      return doneCallBack(false, false); 
     } 
    }; 
} 

router.get('/:widgetnum', function(req, res, next) { 
    //validate widgetnum format 
    var widgetnum = req.params.widgetnum; 
    if (!valid_e164(widgetnum)) { 
     var retval = {"res":false, "msg":"malformed widget"}; 
     res.send(JSON.stringify(retval)); 
    } 
    console.log('scanning db for: widget:' + widgetnum + "*"); 
    redis.send_command("SCAN", [0, "MATCH", "widget:" + widgetnum + "*", "COUNT","1000"], function (err, reply) { 
     if (err) { 
      res.send(JSON.stringify({"res":false,"msg":"no matching widget records found"})); 
     } 
     if (reply) {      
      if (reply[1].length == 2) { 
       //queryfordefault rule 
       async.map(reply[1], queryhgetall_default_rule, function(err, results) { 
        console.log('inside here!'); 
        res.send(JSON.stringify(results)); 
       }); 
      } else { 
       async.map(reply[1], id_rule, function (err, iteration_results) { 

        if (err) { 
         res.send(JSON.stringify("false")); 
        } 
        if (iteration_results) {      
         res.send(JSON.stringify(iteration_results)); 
        }      
       }); 
      } 
     } 
    }); 

}); 

37行是我把我的第一次查询传送至Redis的数据库,并返回结果的数组。

第49-56行是异步方法,它为结果集中的每个结果调用我的迭代器方法...一次。

第18行是我试图将数据从迭代器返回到异步方法。

问题

  1. 很明显,我弄乱的东西了我要回我的数据,因此这将是我的第一个问题的方式 - 你可以看到我在做什么错。

  2. 一旦我找到了我要找的东西,我该如何停止通过回复[1](第49行)进行迭代?

回答

0
  1. 邮报queryhgetall_default_rule和id_rule也代码。但是首先将所有这些都分解到不同的模块中,并在没有HTTP请求的情况下自行测试。

  2. 参见http://caolan.github.io/async/docs.html#.some

还应考虑承诺,Promise.any和await(需要巴贝尔)只是一个for循环做一个在时刻。这些是需要一些时间学习的有用的主题。