首页 > 解决方案 > 在继续代码之前让机器人等待一段时间

问题描述

有没有办法让机器人在继续代码之前等待一段时间(例如 5 秒)?我需要类似的东西:

client.on('messageCreate', message => { 
message.channel.send('1st message')
wait(5000)
message.channel.send('2nd message')
wait(5000) 
message.channel.send('3rd message')
})

就像许多人建议的那样,我尝试使用setInterval,但这似乎不是我的解决方案。我也不能使用await setTimeout(time),因为SyntaxError: await is only valid in async functions and the top level bodies of modulesTypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000

标签: javascriptnode.jsdiscorddiscord.js

解决方案


您可以使用 Node 的Util库进行承诺。 然后使回调异步。setTimeoutmessageCreate

const wait = require('util').promisify(setTimeout);

client.on('messageCreate', async message => { 
   message.channel.send('1st message')
   await wait(5000)
   
   message.channel.send('2nd message')
   await wait(5000) 
   
   message.channel.send('3rd message')
})

推荐阅读