英文:
NodeJS How to wait for a function before closing the script
问题
我必须使用我的 Telegram 机器人 发送一条消息,但我必须在执行之前停止代码
console.log("您不应该看到这个文本");
我无法发送消息,而不是 Telegram 机器人的问题,因为如果我删除 process.exit()
,消息会成功发送。
我应该怎么做才能发送一条消息然后关闭代码?
我的代码:
const TelegramBot = require("node-telegram-bot-api");
const token = 'xxxxx';
const bot = new TelegramBot(token);
bot.sendMessage(MyTelegramID, '测试');
process.exit()
console.log("您不应该看到这个文本");
英文:
I have to send a message with my telegram bot but I have to stop the code before executing
consloe.log("You shouldn't see this text");
I can't send the message, instead, it is not a problem of the TelegramBot because if I remove process.exit()
the message is sent successfully.
What should I do to send a message then close the code?
My code:
const TelegramBot = require("node-telegram-bot-api");
const token = 'xxxxx';
const bot = new TelegramBot(token);
bot.sendMessage(MyTelegramID, 'test');
process.exit()
console.log("You shouldn't see this text");
答案1
得分: 0
sendMessage
是一个异步函数,它返回一个承诺(Promise)。
你应该使用 then
或 await
:
bot.sendMessage(MyTelegramID, 'test').then(() => {
process.exit();
console.log("你不应该看到这个文本");
});
或者
(async () => {
await bot.sendMessage(MyTelegramID, 'test');
process.exit();
console.log("你不应该看到这个文本");
})();
英文:
sendMessage
is an asynchronous function and it returns a promise.
You should use then
or await
:
bot.sendMessage(MyTelegramID, 'test').then(() => {
process.exit();
console.log("You shouldn't see this text");
});
or
(async () => {
await bot.sendMessage(MyTelegramID, 'test');
process.exit();
console.log("You shouldn't see this text");
})();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论