For the code to work, client.commands
must be an object that contains the imported array created in coin.js
.
(为了使代码正常工作, client.commands
必须是一个包含在coin.js
创建的导入数组的对象。)
.get
must be a function on the client.commands
object that returns the desired object within the coin.js array.
(.get
必须是client.commands
对象上的一个函数,该函数返回coin.js数组内的所需对象。)
To await the output of execute
, it must executed be within an asynchronous function (unless you're using bleeding-edge JS).
(为了等待execute
的输出,它必须在异步函数中执行(除非您使用的是最新的JS)。)
You should also execute it in a try/catch
block, which will eliminate the 'Unhandled Rejection' error.(您还应该在try/catch
块中执行它,这将消除“未处理的拒绝”错误。)
// index.js
const coins = require('./coin.js')
const client = {
commands: {
cmds: [...coins],
get(cmd) {
return commands.cmds.filter(item => item.name === cmd)
}
}
}
const doThing = async () => {
try {
switch (cmd) {
case 'coinflip':
await client.commands.get('coinflip').execute(msg, args)
break
}
} catch (err) {
console.error(err)
}
}
;(async () => {
const cmd = 'coinflip'
await doThing(cmd)
})()
// coins.js
module.exports = [
{
name: "coinflip",
async execute(message, args) {
//coinflip code here
}
}
]
This seems like overkill though and could be simplified as:
(不过,这似乎有些过分,可以简化为:)
// index.js
const coinflip = require('./coin.js')
const client = {
commands: {
coinflip
}
}
const doThing = async cmd => {
try {
await client.commands[cmd].execute(msg, args)
} catch (err) {
console.error(err)
}
}
;(async () => {
const cmd = 'coinflip'
await doThing(cmd)
})()
// coins.js
module.exports = {
async execute(message, args) {
//coinflip code here
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…