問題描述
有沒有辦法讓機器人在繼續代碼之前等待一段時間(例如 5 秒)?我需要類似的東西:
Is there any way to make a bot wait for some time (for example 5 seconds) before continuing the code? I need something like:
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 僅在異步函數和模塊的頂層主體中有效
和 TypeError [ERR_INVALID_CALLBACK]:回調必須是一個函數.收到5000
I tried using setInterval
, like many people suggest, but that doesn't seem to be a solution for me.
Also I can't use await setTimeout(time)
because of SyntaxError: await is only valid in async functions and the top level bodies of modules
and TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000
推薦答案
你可以promisify setTimeout
與 Node 的 Util 庫.然后使 messageCreate
回調異步.
You can promisify setTimeout
with Node's Util library. Then make the messageCreate
callback asynchronous.
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')
})
這篇關于在繼續代碼之前讓機器人等待一段時間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!