问题描述
我对JavaScript或NodeJS并不十分了解,但是我使用discord.js
编写了一个discord机器人,该机器人具有自定义插件框架和bunyan
来进行日志记录。我在执行此插件之前将log
对象传递给该插件,因此我可以在不同的插件中保留相同的记录器,他们只需调用this.log
即可获取它。
问题是,当我执行一个promise并传递一个回调函数时,没有引用this.log
,因为该函数超出了作为插件的对象的范围,因此我必须有效地使用全局的东西,可以在then
和catch
方法中将其放入回调。
示例代码失败,如您所愿:
var myPlugin = (function () {
return {
myFunction: async function(message) {
message.guild.channels.create(category,{
type: 'category'
})
.then(function(channel) {
channelID = channel.id;
this.log.debug(`Set channelID to ${channelID}`);
})
.catch(function(error) {
message.reply("Whoops,I hit an error. Please try again later.")
this.log.error(`Error while making category`)
});
}
可以预见的是,失败是因为this.log
超出了回调的范围:
(node:8112) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'error' of undefined
at C:\Users\tunacado\Documents\GitHub\myproject\src\plugins\test.js:46:38
at processticksAndRejections (internal/process/task_queues.js:93:5)
我应该只提供一个全局记录程序插件集来解决这个问题,还是有一个更好的方法来使Logger进入回调函数,而不仅仅是所有插件都可以使用第二个全局范围的记录程序?我曾考虑编写一种定义的方法,然后直接传入而不是匿名函数,但是我担心,因为从技术上讲,this.log
直到插件系统中的某个初始化步骤才存在。
赞赏最佳做法。谢谢!
编辑:
fromMessageHandlePromiseError: function(error) {
message.reply("Whoops,I hit an error doing that. Please try again later.");
this.log.error(`Error while making category`);
}
我只做.catch(fromMessageHandlePromiseError)
,它的工作原理是this
属于对象本身,但是不确定这种理想情况还是我还在做一些愚蠢的事情。谢谢!
编辑2:
@MauriceNino要求我显示如何通过记录器,对不起,我没有首先分享。
它是在我的index.js
中完成的,定义如下:
// Set up logging
const { DEBUG } = require('bunyan');
var Logger = require('bunyan');
const log = new Logger({
name: 'mybot',streams: [
{
stream: process.stdout,level: config.get('bot.logLevel')
}]
}
);
// Load plugins
var loadplugins = require('plugin-system');
let plugins;
loadplugins(
{
paths: [
__dirname + `/src/plugins/`
]
},log)
.then(function onSuccess(loadedplugins) {
log.info(`Loaded plugins: ${loadedplugins}`);
plugins = loadedplugins;
plugins.forEach(function(plugin) {
plugin.config = config;
plugin.log = log;
// Allow plugins to specify their own startup methods
// post-construction after config is passed
if(typeof plugin.initialize === "function") {
plugin.initialize()
}
})
})
.catch(function onError(err) {
log.error(`Error loading plugins: ${err}`);
})
因此,我将每个config
和log
传递给每个插件以获取全局配置和全局记录器。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)