global variable is not updating using nodejs

2019-09-01 02:55发布

I have below global variable and trying to update in diffrent methods

var companyName;

In this method i am getting company name and can able to print the companyName in terminal

var once = async function(myDB) {
    if(once.done) return;

    companyName = await myCacheData.defaultCompany();
    console.log('Company inside once :' + companyName);
}; 

In this method i am trying to get updated company name, which one is updated in side once() function. but when i tried to print in terminal it is showing undefined.

db.dbConnect(function (err) {
    if (err) {
        process.exit(1)
    }
    else {
        myDB = db.getDBConnection();
        app.myDB = myDB;
        
        once(myDB);

        console.log('Company inside db call :' + companyName);
    }
});

1条回答
聊天终结者
2楼-- · 2019-09-01 03:17

try to change this:

once(myDB);

console.log('Company inside db call :' + companyName);

to :

once(myDB).then(v=>console.log('Company inside db call :' + companyName)).catch(v=>console.log('error',v))

because once(myDB) is async and returns a promise you can put the callback in the promise.then(v=>/*your callback*/)

查看更多
登录 后发表回答