繁体   English   中英

我的睡眠 function 不适用于某些命令,我该如何解决? (discord.js)

[英]My sleep function not working for certain commands, how do I fix it? (discord.js)

我的 sleep function 仅适用于某些命令(在代码中); 像这里:

if (message.author.id != dev_ids) return message.channel.send("You don't have permission to use this command")

        let msg = await message.channel.send("Fetching link...")
        await sleep(2000)
        msg.edit(`Check your DMs <@${message.author.id}>`)
        message.author.send(`Bot Logs: https://dashboard.heroku.com/apps/apricot-host/logs\nAny problems? DM <@750436479540527145>`)

但不适用于此命令代码:

message.channel.send("Pinging... <a:870735815062462464:878533686499356683>").then(async m => {
            var ping = m.createdTimestamp - message.createdTimestamp;

            await sleep(1000)

            var embed = new Discord.MessageEmbed()
                .setColor("#ffffff")
                .setAuthor(`${ping}ms`)

            m.delete()
            m.channel.send("Pong! :ping_pong:", embed)
        })

我从上面的代码中收到一条错误消息:

(node:4) UnhandledPromiseRejectionWarning: TypeError: sleep is not a function
     at /app/commands/General/ping.js:12:19
     at processTicksAndRejections (internal/process/task_queues.js:95:5)
 (Use `node --trace-warnings ...` to show where the warning was created)
 (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

在你说 function 没有定义之前,我已经在我的索引文件中全局定义了 function

const sleep = (ms) => { 
        return new Promise(resolve => 
            setTimeout(resolve, ms)
            );
      }

有什么修复吗?

在 node.js 中,如果您在index.js文件中声明一个变量,它在您的ping.js文件中将不可用。 虽然你说你“已经在全球范围内定义了 function” ,但它不是全球性的。 它仅在您的index.js文件中可用。

如果要在其他文件中使用这个 function,可以导出:

// index.js
// ...
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
module.exports = { sleep }
// ...

并将其导入其他文件:

// ping.js
// ...
const { sleep } = require('../../index.js') // make sure the path is correct
// ...

现在,您可以在其他文件中使用sleep

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM