nodejs async如何设置回调

时间:2015-12-10 14:12:17

标签: node.js asynchronous timer

我有以下代码正常工作。

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);
            }

        });

}

现在我想使用async来确保 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);
            }

        });

});

由于我的原始函数没有任何回调,并且因为异步需要回调,所以我试图在function4&中编写回调函数。 function5 - 但我想我没有正确编码。

我在回调存在的行中收到错误,指出" TypeError:undefined不是函数"。

我如何纠正这个?

相关问题2:当前代码具有定时器功能,其中function4,function5和function6与预设定时器一起运行。如果异步工作,我如何定义一个计时器,其中功能组合4,5& 6基于预设定时器工作?

对于长代码感到抱歉 - 我是nodejs的新手并且已经移交了此代码,并且我正在尝试进行此更改。

感谢您的指导。

1 个答案:

答案 0 :(得分:0)

您可以改为使function4和function5返回promise,然后只有在function4&function和promise5的承诺得到解决后才执行function6。