2015-12-10 46 views
0

我有以下代码工作正常。nodejs异步如何设置回调

var config = require('./config'); 
var cheerio = require('cheerio'); 
var myhttp = require('./myHttp'); 
var stringHelper = require('./stringHelper'); 
var Base64 = require('./base64.js').Base64; 
var Encrypt = require('./Encrypt.js'); 
var myEncode = require('./Encode.js'); 
var rules = require('./rules'); 
var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 }); 
var mysql = require('mysql'); 
delete require.cache[require.resolve('./requestLogin1.js')] 
var myvar = require('./requestLogin1.js'); 
var connection = mysql.createConnection(
    { 
     host : 'localhost', 
     user : 'root', 
     password : 'abc', 
     database : 'abcd' 
    } 
); 
connection.connect(function(err) { 
    if (err) { 
    console.log('error connecting: ' + err.stack); 
    return; 
    } 

}); 

var timerOB; 
var timerMW; 
var timerP; 
var timerTL; 
var news = { 
    'mw': [], 
    'ob': [], 
    'all': {}, 
}; 
var status = false; 



function round(rnum, rlength) { 
    return newnumber = Math.round(rnum * Math.pow(10, rlength))/Math.pow(10, rlength); 
} 
function roundup(rnum, rlength) { 
    return newnumber = Math.ceil(rnum * Math.pow(10, rlength))/Math.pow(10, rlength); 
} 
function rounddown(rnum, rlength) { 
    return newnumber = Math.floor(rnum * Math.pow(10, rlength))/Math.pow(10, rlength); 
} 

function function1(_html) { 
    console.log('function1 run') 
    var $ = cheerio.load(_html); 
    var v_lgnid = $('#userId').attr('value'); 
    var v_psswrd = config.password; 
    var v_data = v_lgnid + "|" + v_psswrd; 
    var _key = $('#accntid').attr('value'); 
    if (_key) { 
     v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, _key , "256")); 
     v_data = escape(v_data); 
     myhttp.get(
      'https://example.com/ValidPassword.jsp?' + $('#name').attr('value') + "=" + v_data, 
       function (_htmlShowImage) { 
       if (_htmlShowImage && _htmlShowImage.trim() == "OK") { 
        function2(); 
       } else { 
        console.log('Login Fail'); 
       } 
      }); 
    } else { 
     login(); 
     console.log('Encrypt password error'); 
    } 

} 

function function2() { 
    myhttp.get(
     'https://example.com/QuestionsAuth.jsp', 
     function (_htmlShowImage) { 
      var $ = cheerio.load(_htmlShowImage); 
      var sLoginID = $('#sLoginID').attr('value'); 
      var Answer1 = config.answer1; 
      var Answer2 = config.answer2; 
      var Index1 = $('#st1').attr('value'); 
      var Index2 = $('#st2').attr('value'); 

      var v_data = sLoginID + "|" + Answer1 + "|" + Answer2 + "|" + Index1 + "|" + Index2; 

      v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, $('#key_questauth').attr('value'), "256")); 
      v_data = escape(v_data); 
      myhttp.get(
       'https://example.com/ValidAnswers.jsp?' + $('#name_questauth').attr('value') + "=" + v_data, 
        function (_htmlShowImage) { 

        if (_htmlShowImage && _htmlShowImage.trim() == "OK") { 
         //rootCallback(); 
         myhttp.get(
          'https://example.com/DefaultLogin.jsp', 
        function (_html) { 
           console.log('Login sucess') 
           stringHelper.SaveFileCookies('abcd.txt', myhttp.loadCookie(), 'save cookie login sucess'); 


           if (timerMW) { 
            clearTimeout(timerMW); 
           } 
           timerMW = setTimeout(function6, config.DelayExtractMW); 


           if (timerOB) { 
            clearTimeout(timerOB); 
           } 
           timerOB = setTimeout(function5, config.DelayExtractOB); 

           if (timerP) { 
            clearTimeout(timerP); 
           } 
           timerP = setTimeout(function4, config.function4); 

          }); 

        } else { 
         console.log('Login Fail - timer'); 
        } 
       }); 
     }); 
} 
var login = function() { 
    if (timerMW) { 
     clearTimeout(timerMW); 
    } 
    if (timerOB) { 
     clearTimeout(timerOB); 
    } 
    if (timerP) { 
     clearTimeout(timerP); 
    } 
    if (timerTL) { 
     clearTimeout(timerTL); 
    } 

    myhttp.init(); 
    myhttp.post(
     'https://example.com/ShowImage.jsp', 
       { "requiredLogin": myEncode.Convert(config.uname) }, 
       function (_htmlpost) { 
      if (_htmlpost) { 
       function1(_htmlpost); 
      } else { 
       if (timerTL) { 
        clearTimeout(timerTL); 
       } 
       timerTL = setTimeout(login, config.DelayNestError); 
      } 
     }); 

} 
exports.login = login; 

function function3() { 
    return { 
     TS: '', 
     MWP: 0, 
     LTP: 0, 
     NQ: 0, 
     OBBP: '', 
     OBSP: '', 
     CurrTime: 0, 
     rules: {} 
    }; 
} 



function function4() { 
    status = false; 
    myhttp.get('https://example.com/PB.jsp?Exchange=', 
      function (_html) { 
     if (_html && _html.length > 10) {   
      news.pn = {}; 
      $ = cheerio.load(_html); 

      $('tr[id^="TR"]').each(function() { 
       status = true; 
       var symbol = $('td:nth-child(3)', this).text().trim(); 
       var objob = { 
        'NQ': parseInt($('td:nth-child(11)', this).text().trim()), 
       }; 

       var post = { 
         'symbol': symbol, 
         'nq': objob.NQ 
         }; 


      connection.query('INSERT INTO NP SET ?', post, function (err,result){ 
      if (err) 
      {console.log("NP sql insert error : " +symbol);} 
      else { 
       console.log("data inserted into NP Table : " +symbol); 
      } 
     }); 




       var objstock = news.all[symbol]; 


if (typeof objstock!='undefined') { 
       objstock.NQ = objob.NQ; 
       news.pn[symbol] = objob; 
       news.all[symbol] = objstock; 

       if (status) { 
       io.emit('news', news); 

      } 
       } 
    else    
{ 
    console.log('symbol not found'); 
} 
      }); 





      if (timerP) { 
       clearTimeout(timerP); 
      } 
      console.log('setTimer function4:' + config.DelayExtractPn); 
      timerP = setTimeout(function4, config.DelayExtractPn); 


     } 


      connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){ 
      if (err) 
      {console.log("CQ06 skipped: ");} 
      else { 
       console.log("Step 6 - Master1 tbq data updated"); 
      } 
     }); 



      connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){ 
      if (err) 
      {console.log("CQ07 skipped: ");} 
      else { 
       console.log("Step 7 - Master1 tsq data updated"); 
      } 
     }); 



    }); 

} 

function function5() { 
    status = false; 
    myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All', 
      function (_html) { 
     if (_html && _html.length > 10) { 
      $ = cheerio.load(_html); 
      console.log('OB - Step 2 - html loaded for parsing'); 
      news.ob = []; 
      $('tr[id^="TR"]').each(function() { 
       var statusOrder = $('td:nth-child(20)', this).text().trim(); 
       if (statusOrder.toLowerCase().indexOf('open') >= 0) { 
        status = true; 
        var objob = { 
         'symbol': $('td:nth-child(6)', this).text().trim(), 
         'buysell': $('td:nth-child(9)', this).text().trim(), 
         'ordernumber': $('input[name="Select"]', this).attr('value'), 
        }; 


        var objstock = news.all[objob.symbol]; 

       objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:""; 
        objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:""; 

        news.ob.push(objob); 

       } 

      }); 

      if (status) { 
       io.emit('news', news); 
      } 
      if (timerOB) { 
       clearTimeout(timerOB); 
      } 
      timerOB = setTimeout(function5, config.DelayExtractOB); 
     } 

    }); 

} 



function function6() { 
    myhttp.get(
     'https://example.com/MW.jsp?', 
     function (_html) { 
      if (_html && _html.length > 10) { 
       var $ = cheerio.load(_html); 
       status = false; 
       news.mw = []; 
       var countCheckRule = 0; 
       var countCheckedRule = 0; 
       var tmpall = {}; 
       $('tr[onclick]').each(function() { 
        status = true; 
        var data1 = $("input[onclick*='Apply(']", this).attr('onclick'); 
        var arrdata1 = data1.split("','"); 
        var stockid = arrdata1[1].split('|')[0]; 
        var symbol = $('td:nth-child(3)', this).text().trim(); 
        var price = parseFloat($('td:nth-child(4)', this).text().trim()); 
        var cTime = stringHelper.getIndiaTime(); 
        var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds) 
        news.mw.push({ 
         'symbol': symbol, 
         'price': price, 
         'stockid': stockid, 
         'CurrTime': CurrTime, 
        }); 


        var objstock = news.all[symbol]; 
        if (!objstock) { 
         objstock = function3(); 
        } 
        if (!news.pn[symbol]) { 
         objstock.NQ = 0; 
        } 

        var notfoundob = true; 
        for (var symbolkey in news.ob) { 
         if (news.ob[symbolkey].symbol == symbol) { 
          notfoundob = false; 
         } 
        } 
        if (notfoundob) { 
         objstock.OBBP = ""; 
         objstock.OBSP = ""; 

        } 


        objstock.TS = symbol;//trade symbol 
        objstock.MWP = stockid;//trade id 
        objstock.LTP = price; 
        objstock.CurrTime = CurrTime; 


        rules.checRules(objstock, myhttp, function (rules_res) { 
         objstock.rules = rules_res; 
         tmpall[symbol] = objstock; 

        }); 

        countCheckRule++; 
       }); 

       rules.rule12(tmpall, function (_tmpall) { 
        tmpall = _tmpall; 

       }); 
       news.all = tmpall; 

       if (!status) { 
        login(); 
        console.log('MW - Step 9 - logged out'); 

       } else { 

        io.emit('news', news); 
        if (timerMW) { 
         clearTimeout(timerMW); 
        } 
        timerMW = setTimeout(function6, config.DelayExtractMW); 
       } 

      } else { 
       if (timerMW) { 
        clearTimeout(timerMW); 
       } 


       timerMW = setTimeout(function6, config.DelayExtractMW); 
      } 

     }); 

} 

现在我想用异步确保function6是function4 & function5运行后才能运行。

我试图了解从各种论坛异步和如下改变了代码:

var async = require('async'); //line added 

// change made 


async.parallel([ 

function function4(callback) { 
    status = false; 
    myhttp.get('https://example.com/PB.jsp?Exchange=', 
      function (_html) { 
     if (_html && _html.length > 10) {   
      news.pn = {}; 
      $ = cheerio.load(_html); 

      $('tr[id^="TR"]').each(function() { 
       status = true; 
       var symbol = $('td:nth-child(3)', this).text().trim(); 
       var objob = { 
        'NQ': parseInt($('td:nth-child(11)', this).text().trim()), 
       }; 
       console.log('Posn - Step 3A - Found position:' + symbol); 

       var post = { 
         'symbol': symbol, 
         'nq': objob.NQ 
         }; 


      connection.query('INSERT INTO NP SET ?', post, function (err,result){ 
      if (err) 
      {console.log("NP sql insert error : " +symbol);} 
      else { 
       console.log("data inserted into NP Table : " +symbol); 
      } 
     }); 




       var objstock = news.all[symbol]; 


if (typeof objstock!='undefined') { 
       objstock.NQ = objob.NQ; 
       news.pn[symbol] = objob; 
       news.all[symbol] = objstock; 

       if (status) { 
       io.emit('news', news); 

      } 
       } 
    else    
{ 
    console.log('symbol not found'); 
} 
      }); 





      if (timerP) { 
       clearTimeout(timerP); 
      } 
      console.log('setTimer function4:' + config.DelayExtractPn); 
      timerP = setTimeout(function4, config.DelayExtractPn); 


     } 


      connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){ 
      if (err) 
      {console.log("CQ06 skipped: ");} 
      else { 
       console.log("Step 6 - Master1 tbq data updated"); 
      } 
     }); 



      connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){ 
      if (err) 
      {console.log("CQ07 skipped: ");} 
      else { 
       console.log("Step 7 - Master1 tsq data updated"); 
      } 
     }); 

    callback(); //line added 

    }); 

}, 

function function5(callback) { 
    status = false; 
    myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All', 
      function (_html) { 
     if (_html && _html.length > 10) { 
      $ = cheerio.load(_html); 
      console.log('OB - Step 2 - html loaded for parsing'); 
      news.ob = []; 
      $('tr[id^="TR"]').each(function() { 
       var statusOrder = $('td:nth-child(20)', this).text().trim(); 
       if (statusOrder.toLowerCase().indexOf('open') >= 0 || statusOrder.toLowerCase().indexOf('trigger pending') >= 0) { 
        status = true; 
        var objob = { 
         'symbol': $('td:nth-child(6)', this).text().trim(), 
         'buysell': $('td:nth-child(9)', this).text().trim(), 
         'ordernumber': $('input[name="Select"]', this).attr('value'), 
        }; 


        var objstock = news.all[objob.symbol]; 

       objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:""; 
        objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:""; 

        news.ob.push(objob); 

       } 

      }); 

      if (status) { 
       console.log('OB - Step 5 - pushed to html page'); 
       io.emit('news', news); 
      } 
      if (timerOB) { 
       clearTimeout(timerOB); 
      } 
      timerOB = setTimeout(function5, config.DelayExtractOB); 
     } 
    callback(); //line added 
    }); 

} 

], 

function function6() { 
    myhttp.get(
     'https://example.com/MW.jsp?', 
     function (_html) { 
      if (_html && _html.length > 10) { 
       var $ = cheerio.load(_html); 
       status = false; 
       news.mw = []; 
       var countCheckRule = 0; 
       var countCheckedRule = 0; 
       var tmpall = {}; 
       $('tr[onclick]').each(function() { 
        status = true; 
        var data1 = $("input[onclick*='Apply(']", this).attr('onclick'); 
        var arrdata1 = data1.split("','"); 
        var stockid = arrdata1[1].split('|')[0]; 
        var symbol = $('td:nth-child(3)', this).text().trim(); 
        var price = parseFloat($('td:nth-child(4)', this).text().trim()); 
        var cTime = stringHelper.getIndiaTime(); 
        var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds) 
        news.mw.push({ 
         'symbol': symbol, 
         'price': price, 
         'stockid': stockid, 
         'CurrTime': CurrTime, 
        }); 


        var objstock = news.all[symbol]; 
        if (!objstock) { 
         objstock = function3(); 
        } 
        if (!news.pn[symbol]) { 
         objstock.NQ = 0; 
        } 

        var notfoundob = true; 
        for (var symbolkey in news.ob) { 
         if (news.ob[symbolkey].symbol == symbol) { 
          notfoundob = false; 
         } 
        } 
        if (notfoundob) { 
         objstock.OBBP = ""; 
         objstock.OBSP = ""; 

        } 


        objstock.TS = symbol;//trade symbol 
        objstock.MWP = stockid;//trade id 
        objstock.LTP = price; 
        objstock.CurrTime = CurrTime; 


        rules.checRules(objstock, myhttp, function (rules_res) { 
         objstock.rules = rules_res; 
         tmpall[symbol] = objstock; 

        }); 

        countCheckRule++; 
       }); 
       //new check rules 

       rules.rule12(tmpall, function (_tmpall) { 
        tmpall = _tmpall; 

       }); 
       news.all = tmpall; 

       if (!status) { 
        login(); 

       } else { 

        io.emit('news', news); 
        if (timerMW) { 
         clearTimeout(timerMW); 
        } 
        timerMW = setTimeout(function6, config.DelayExtractMW); 
       } 

      } else { 
       if (timerMW) { 
        clearTimeout(timerMW); 
       } 


       timerMW = setTimeout(function6, config.DelayExtractMW); 
      } 

     }); 

}); 

因为我原来的功能没有任何回调,并且由于异步需要回调,我试图代码函数4中的回调函数5 - 但我想我没有正确编码它。

我得到一个错误,其中回调存在的状态“TypeError:undefined不是一个函数”。

我该如何纠正?

相关问题2:当前代码有一个定时器功能,其中函数4,函数5和函数6以预设定时器运行。如果异步工作,我该如何定义一个定时器,从而基于预设的定时器,功能的组合集合起作用?

对不起,关于长码 - 我是nodejs的新手,并且将这段代码交给了我,并试图让这个更改生效。

感谢您的指导。

+0

你不应该在异步模块 –

+0

中使用'parallel'但'waterfall'方法来指导如何在瀑布方法中对回调进行编码 - 因为定义回调似乎是卡住的地方。 –

+0

如果您可以将您发布的代码压缩成更相关的内容,我将不这样做,否则我很抱歉无法阅读所有这些内容。 –

回答

0

您可以改为使function4和function5返回promise,然后只有在函数4和函数5的promise都解析后才执行function6。

+0

你能指示我一些这方面的例子吗?尤其是因为我不确定如何在函数4和函数5中定义回调函数。 –