Node js 不允许 .on 在初始化客户端之前监听[重复]

问题描述 投票:0回答:1

我正在尝试制作一个whatsapp聊天机器人,有一个名为whatsapp-web-js的包用于此目的。唯一的问题是我在实现这个时遇到了问题,因为我对节点 Javascript 和异步代码非常陌生。

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');
});

问题在于,我抛出了一个空指针错误,因为客户端未初始化,因为它正在等待 Moongoose 数据库连接,但节点已经想要监听“就绪”事件。如何让节点在监听之前等待客户端初始化?

javascript node.js asynchronous whatsapp
1个回答
1
投票

将客户端代码移至初始化时。

    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.
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.