【问题标题】:What to do if setTimeout doesn't give any output如果 setTimeout 没有给出任何输出怎么办
【发布时间】:2023-03-17 01:00:01
【问题描述】:

我正在编写一个电报机器人(使用 Telegraf),需要以特定的顺序以一定的时间间隔发送 3 条消息。然后我在 VC 代码中运行这段代码,它运行良好。当我在服务器 (AWS) 上部署相同的代码时,它就不起作用了。我没有从 setTimeout 函数得到任何输出。

const executeAfterGivenTime = (func, time) => new Promise(res => setTimeout(() => res(func()), time));

function newOne(ctx){
    ctx.reply('coo');
}

function newTwo(ctx){
    ctx.reply('boo');
}

function newThree(ctx){
    ctx.reply('foo');
}

bot.command('dit', async (ctx) => {
      await executeAfterGivenTime(() => newOne(ctx), 0);
      await executeAfterGivenTime(() => newTwo(ctx), 6000);
      await executeAfterGivenTime(() => newThree(ctx), 12000);
})

【问题讨论】:

  • 我得到“coo”,但没有得到“boo”和“foo”。
  • 指定您使用的机器人库。
  • @KevinWelch Telegraf

标签: javascript settimeout telegram-bot telegraf


【解决方案1】:

您必须将 setTimeout 包装在 Promise 中才能获得所需的结果。

阅读Promise 文档here

const executeAfterGivenTime = (func, time) =>
  new Promise((res) => setTimeout(() => res(func()), time));

function newOne(ctx) {
  ctx.reply("coo");
}

function newTwo(ctx) {
  ctx.reply("boo");
}

function newThree(ctx) {
  ctx.reply("foo");
}

// Dummy bot for testing
const bot = {
  command: (str, fn) => {
    console.log(`Command "${str}" detected. Executing funtion`);
    fn();
  },
};

// Dummy ctx for testing
const ctx = {
  reply: (txt) => {
    console.log(txt);
  },
};

bot.command("dit", async () => {
  await executeAfterGivenTime(() => newOne(ctx), 0);
  await executeAfterGivenTime(() => newTwo(ctx), 6000);
  await executeAfterGivenTime(() => newThree(ctx), 12000);
});

【讨论】:

  • 但是如果我想调用其他函数呢?有必要。我试过这个 ``` const getValueAfterGivenTime = (value, time) => new Promise(res => setTimeout(() => res(value), time)) const botCommand = async(ctx) => { await getValueAfterGivenTime( newOne(ctx), 0);等待 getValueAfterGivenTime(newTwo(ctx), 6000);等待 getValueAfterGivenTime(newThree(ctx), 12000); } bot.command('dit', ctx => { botCommand(ctx); }) ``` 显然有问题,因为你不能将函数的结果传递给 setTimeout
  • @Christopher 通过一些小的改动来解决它的方法相同。我已经更新了答案。看看它,如果您仍有任何问题,请添加评论
  • 所有函数都有ctx参数。我试图将您的 executeAfterGivenTime 更改为 => const executeAfterGivenTime = (func, time, arg) => new Promise(res => setTimeout((arg) => res(func(arg)), time));像这样等待: await executeAfterGivenTime(newOne, 0, ctx);这让只显示“coo”
  • 你真的不需要改变executeAfterGivenTime函数。我对答案做了一些更改,请看一下。
  • 我已经更新了我最初的消息中的代码。所以这就是它在程序中的样子。但运行后它不会进一步“咕咕”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
相关资源
最近更新 更多