如何解决如果 setTimeout 没有给出任何输出怎么办
我正在编写一个电报机器人(使用 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);
})
解决方法
您必须将 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);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。