简体   繁体   English

Node.js模块无法通信

[英]Node.js module not communicating

I am in the process of teaching myself node.js by building a personal project. 我正在通过构建个人项目来自学node.js。 I am trying to follow best practices by splitting my code up into separate modules. 我试图通过将代码拆分为单独的模块来遵循最佳实践。 However, I've run into a problem where one of my modules is communicating back to the caller module. 但是,我遇到了一个问题,其中我的一个模块正在与调用方模块通信。 I've used callback functions and events, but the caller module never gets anything back from the called module, unless the called module returns a value immediately. 我已经使用了回调函数和事件,但是调用者模块从不从被调用模块获取任何东西,除非被调用模块立即返回一个值。 Please look at the below code and let me know what I'm missing: 请查看下面的代码,让我知道我所缺少的内容:

blogs.controller.js (caller module) blogs.controller.js(调用方模块)

var ImageParser = require('../../components/parsers/ImageParser.js');
.....
var imageParser = new ImageParser();
imageParser.on('imagesParsed', function(){
console.log('test)});

ImageParser.js (called module) ImageParser.js(称为模块)

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var ImageParser = function(){
    this.emit('imagesParsed');
};

util.inherits(ImageParser, EventEmitter);

module.exports = ImageParser;

Within the ImageParser function, I can listen for the event, but outside of it, I can't. 在ImageParser函数中,我可以监听事件,但是在事件之外,我不能监听。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks 谢谢

I actually found my answer in an answer to another question, answered by @linus-g-thiel Also, thanks to @Pointy 我实际上在另一个问题的答案中找到了答案,答案由@ linus-g-thiel回答此外,感谢@Pointy

Turns out I need to emit the event from a method, not the constructor, and the listener needs to be BEFORE the method call. 原来,我需要从方法而不是构造函数发出事件,并且侦听器需要在方法调用之前。 It's working now. 现在正在工作。

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

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