如果我过早地在robot.brain中设置一个值,它会被hubot-redis-brain覆盖

时间:2017-10-24 18:32:55

标签: javascript hubot

如果我在我的脚本robot.brain的正文中初始化module.exports中的某个媒体资源,则它无法正常工作(请参阅下面的代码)。如果我在响应期间初始化它,它可以工作。我的假设是它被hubot-redis-brain改写了吗?我该如何以一种很好的方式解决它?

module.exports = (robot) => {
    robot.logger.debug("Setting the fucking property");
    robot.brain.set("stringproperty", "stringvalue");
    robot.logger.debug("SET!");
    // logs these two entries before 'INFO hubot-redis-brain: Data for hubot brain retrieved from Redis'

    const respondAndLog = (res, message) => {
        robot.logger.debug("Responding: " + message);
        res.reply(message);
    };

    robot.respond(/get_stringproperty/, (res) => {
        respondAndLog(res, `${robot.brain.get("stringproperty")}`);
        // prints null. WTF?
    });

    robot.respond(/get_laterinitializedproperty/, (res) => {
        robot.brain.set("laterinitializedproperty", "laterinitializedvalue");
        respondAndLog(res, `${robot.brain.get("laterinitializedproperty")}`);
    // prints laterinitializedproperty, works OK
    });
};

1 个答案:

答案 0 :(得分:2)

当数据从redis加载或初始化时,

hubot-redis-brain会使robot.brain发出"connected"事件,请参阅[https://github.com/hubotio/hubot-redis-brain/blob/487dd4a9641f35ffb5ae18fb5e1b09e8114c4b70/src/redis-brain.js#L55](see第55和59行。所以这就是它应该如何修复:

robot.brain.on("connected", () => {
    robot.logger.debug("Setting the fucking property");
    robot.brain.set("stringproperty", "stringvalue");
    robot.logger.debug("SET!");
});