javascript – Node js do not allow .on to listen before intializing the client

I’m trying to make a whatsapp chatbot, theres a have a package called whatsapp-web-js for this. The only problem is im running into problems implementing this as im very new to node js and async code.

let client;
    
//Connect to the database to get old persisted session data 

mongoose.connect('mongodb+srv://...url').then(() => {
    //once connected, create new session "client" with persisted data
    const store = new MongoStore({ mongoose: mongoose });
    client = new Client({
        authStrategy: new RemoteAuth({
            store: store,
            backupSyncIntervalMs: 60000
        })
    });
    ready = false;
    client.initialize().then(r => console.log("Initializing whatsapp client"));

    //Generate QR Code if needed
    const qrcode = require('qrcode-terminal');
    client.on('qr', qr => {
        qrcode.generate(qr, {small: true});
    });
});

//Client has saved remote session
client.on('remote_session_saved', () => {
    console.log('Client remote session saved');
});

//Client is ready to send/receive requests
client.on('ready', () => {
    console.log('Client is ready to send/receive requests');
});

the problem lies in the fact that i get thrown a null pointer error because client is not initialized as it is waitting for the moongoose db to connect, but node already wants to listen for the ‘ready’ event. How do i make node wait for the client to get initialized before listening?

Read more here: Source link