Node.js需要在执行函数之前等待循环完成

时间:2016-12-26 04:49:18

标签: javascript node.js asynchronous callback async.js

确定。所以我对节点非常新。我的思绪现在正在回调地狱。我已经阅读了许多类似的问题,但似乎无法让它正常运行。

基本上,我正在通过服务器日志正则表达式解析特定的字符串,我将用它来运行一些SQL查询。我已经让它在较小的规模上工作,不需要循环。

我需要等待所有的ppsid运行_cssPPSID,它生成一个字典对象和我的查询过滤器,然后在查询本身中使用该过滤器运行查询,然后匹配该字典以将结果与从服务器日志解析的数据。

截至目前,此代码已运行,但在第一次迭代后停止。我假设我缺少一个回调或简单的东西,以便脚本可以回到循环。

var ppsDict = new Object();
var ppsList = new Array();

var getURL = function(stdout) {
    console.log('Creating ppsid url key value pairs');
    var url_reg = /http\S+/g;
    var ppsid_reg = /PPS_ID\=[0-9]+/g;
    var ppsid = stdout.toString().match(ppsid_reg);
    var url = stdout.toString().match(url_reg);
    ppsDict[ppsid[0]] = url[0];
    ppsList.push(ppsid[0]);
    console.log(ppsDict);
  };


var getPPSID = function(stdout, prodServer, searchResultProcessed) {
    console.log("Collecting PPSID's");
    var ppsid_reg = /PPS_ID\=[0-9]+/g;
    var selector_reg = /selector\s\S+/g;
    var ppsid = stdout.toString().match(ppsid_reg);
    var selector = stdout.toString().match(selector_reg);
    async.eachSeries(ppsid, function (ppsSelector, next) {
      var urlQ = new urlQuery(prodServer, searchResultProcessed,  ppsSelector);
      _cssPPSID(urlQ, function(err, result) {
         if(err) {
          console.log(err);
        }
        next();
      }) 
    }, function (err) {
        console.log('iterating done');
        //queryProd(ppsList,ppsDict);
    });
}


function urlQuery(prodServer, searchResultProcessed, ppsSelector) {
  this.cssPPSID = "ssh " + prodServer + " 'sudo cat  /mint/logs/topologies/'" + searchResultProcessed + " | grep " + ppsSelector  + " | grep \"Downloading\"";
}

var _cssPPSID = (urlQ) => {
  child_process.exec(urlQ.cssPPSID, ["-m"], (err, stdout, stderr) => {
    if (stdout === 0) {
      console.log('PPS_ID and CSS error combination not found');
      return;
    } else if (err) {
     console.error(err, stderr);
      return;
    }
    getURL(stdout);
  });
};

1 个答案:

答案 0 :(得分:1)

Your async.eachSeries won't work because function _cssPPSID doesn't take a callback as second argument, so the next() is never called.

Try rewriting it like this:

var _cssPPSID = (urlQ, callback) => { 
  child_process.exec(urlQ.cssPPSID, ["-m"], (err, stdout, stderr) => {
    if (err) {
      return callback(err);
    }        
    if (stdout === 0) {
      return callback(new Error('PPS_ID and CSS error combination not found');
    }
    // do stuff here
    callback(null); // null indicates no error has happened
  });
};