如何在方法中调用的promise中将记录器传递给回调函数?

问题描述

我对JavaScript或NodeJS并不十分了解,但是我使用discord.js编写了一个discord机器人,该机器人具有自定义插件框架和bunyan来进行日志记录。我在执行此插件之前将log对象传递给该插件,因此我可以在不同的插件中保留相同的记录器,他们只需调用this.log即可获取它。

问题是,当我执行一个promise并传递一个回调函数时,没有引用this.log,因为该函数超出了作为插件的对象的范围,因此我必须有效地使用全局的东西,可以在thencatch方法中将其放入回调。

示例代码失败,如您所愿:

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}`);
    })

因此,我将每个configlog传递给每个插件获取全局配置和全局记录器。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...