我正在尝试制作一个whatsapp聊天机器人,为此有一个名为whatsapp-web-js的包。唯一的问题是我在实现这个时遇到了问题,因为我对 Node js 和异步代码非常陌生。
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 数据库连接,但节点已经想要监听“就绪”事件。如何让节点在监听之前等待客户端初始化?
将客户端代码移至初始化时。
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.
});
});