0

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);
    }
});
5
  • 3
    you need to await the call of once. Commented Apr 12, 2018 at 7:45
  • myCacheData.defaultCompany(); may be returning nothing Commented Apr 12, 2018 at 7:49
  • Odds are on that db.getDBConnection() is also async and needs to be awaited as well. But in the context of what you told us , then what @RolandStarke already said Commented Apr 12, 2018 at 7:51
  • async function don't block. They return a promise. If you want to wait for their result to be done, you have to use .then() on that promise. Commented Apr 12, 2018 at 7:55
  • let me check @RolandStarke answer Commented Apr 12, 2018 at 8:40

1 Answer 1

1

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*/)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.