Search code examples
javascriptnode.jsasynchronouswhatsapp

Node js do not allow .on to listen before initializing the client


I'm trying to make a whatsapp chatbot, there's a have a package called whatsapp-web-js for this. The only problem is I'm running into problems implementing this as I'm very new to node Javascript 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 waiting 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?


Solution

  • Move client code to when of initializing.

        client.initialize().then(() => {
        console.log('Initializing whatsapp client');
    
        // Generate QR Code if needed
        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');
          // Start listening for the 'ready' event after the client is initialized.
        });
      });