Node.js如何在关闭脚本之前等待函数完成。

huangapple go评论67阅读模式
英文:

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)。
你应该使用 thenawait

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");
})();

Documentation

huangapple
  • 本文由 发表于 2020年1月6日 02:23:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59602919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定