nodejs asynchronous to synchronous

When the project is developed in wechat environment, it needs to obtain access_token for authorized login and user information.

Specially take this function out to encapsulate a custom module

module.exports = new Wechat(con.appid, con.secret, con.url);

appid and secret were written dead before the local configuration file, and later the system backstage could be configured official account.

You need to request configuration parameters from the background. This is a problem.

var wechat = require('./modules/wechat');
var rule = new schedule.RecurrenceRule();
//rule.hour = [0,2,4,6,8,10,12,14,16,18,20,22];
rule.minute = 0;
var j = schedule.scheduleJob(rule, function(){
wechat.getBaseTokenForever();
});
wechat.getBaseTokenForever();

My service will acquire new access_token at startup and every hour, and store it in the database to ensure that it is always effective and used to control the number of requests.

Later, the module was changed to

var data = {};
    request({
        url: con.url + '/Route',
        method: "POST",
        json: true,
        body: {}
    }, function (err, response, body) {
        if (err || body.code != 0) {
            console.log('Failed to get official account configuration '+ Date());
        } else {
            console.log('Get official account configuration '+ Date());
            data = body.data;
        }
    });


module.exports =  function () {
    return new Wechat(data.appid, data.secret, con.url);
};

But the asynchronous effect of nodejs will cause the following code to be executed before the request is completed, resulting in errors.

After multi-party search, async module can be used to asynchronously transynchronize. Only when the previous function performs callback, the next function will execute.  

var async = require('async');
async.waterfall([
    function(callback){
        getWechat();
        function getWechat() {
            if(!wechat().appid){
                setTimeout(function () {
                    getWechat();
                },1000);
                console.log(wechat());
            } else {
                callback(null,wechat())
            }
        }
    },
    function(wechat, callback){   
    
var rule = new schedule.RecurrenceRule(); //rule.hour = [0,2,4,6,8,10,12,14,16,18,20,22]; rule.minute = 0; var j = schedule.scheduleJob(rule, function(){ wechat.getBaseTokenForever(); }); wechat.getBaseTokenForever(); callback(null) } ], function(err, results){ console.log(err) });

Tags: Javascript Database JSON

Posted on Tue, 31 Mar 2020 08:34:50 -0700 by pkellum