0

I have a CustomStore class, in its constructor I connect to a Mongo table. In class I have a saveToken() function that saves data in a table.

class CustomStore extends TokenStore {

    constructor(){
       
        connectDb(function(){
            console.log("Connected to db")
        });
    }

This is the connectDb() function called in the constructor

function connectDb(callback){
    let url = 'mongodb://localhost/zoho_whatsapp';
    let dbName = 'zoho_auth';

    let client = new MongoClient(url, { useNewUrlParser: true });
    client.connect((err) => {
        if (err) { throw err; }

        let db = client.db(dbName);
        let collection = db.collection('oauthtokens');

        callback(collection, client, db);
    });
}

And this is the saveToken() function

saveToken(user, token) {
        console.log("The token is saved");
    }

}

Now I want to call the function from another file

new zohoPersists.CustomStore().saveToken (user, token);

But the function ran before the constructor and I have not yet connected to the Mongo table. Do I need to write a promise function? I do not know enough ...

Thanks

Maxima
  • 69
  • 8
  • *"But the function ran before the constructor"* It didn't. The constructor ran, **began** the asynchronous process of connecting to the DB, and then returned. Then your method was called, apparently the asynchronous process of connecting to the DB was complete (or at least before whatever is really in your callback ran; that part is guaranteed). You'll need to provide a way to tell callers that your instance is actually ready for use, because it isn't ready for use right away (because there's this asynchronous bit). There are several possible ways to do that. You might ... – T.J. Crowder Jun 29 '22 at 07:22
  • ... have the constructor store a promise of the DB connection, then make `saveToken` an `async` function that awaits that promise before doing its work. Or you might make creating an instance a static `async` method that doesn't return the created instance until it's connected to the DB. Or any of several other patterns. – T.J. Crowder Jun 29 '22 at 07:22
  • Thank you. I added the connectDb function to the question, to make it clearer. – Maxima Jun 29 '22 at 08:05
  • [This question's answers](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) will also likely be useful. – T.J. Crowder Jun 29 '22 at 08:44

0 Answers0