简体   繁体   English

为什么我的节点事件回调在事件中显示为undefined?

[英]Why is my node event callback showing up in the event as undefined?

I am trying to pass back a url string as "data" into my eventhandler. 我试图将URL字符串作为“数据”传递回我的事件处理程序中。

My request to the server is " https://172.20.10.6/index.html ". 我对服务器的请求是“ https://172.20.10.6/index.html ”。 The console.log below prints out "/index.html" as I expect. 如我所料,下面的console.log打印出“ /index.html”。

switch(req.method) {
    case 'GET':

    console.log("logged from plugin-https.js: url: " + req.url);

     ee.emit("dataIn", req.url);

     break;

Below is the eventHandler code. 下面是eventHandler代码。
The console.log(data); console.log(data); evaluates to "undefined". 评估为“未定义”。 I am trying to figure out why this is. 我试图弄清楚为什么。 It seems like a pretty straightforward direct callback, so I am wondering why the data is not defined when it shows up in the eventhandling code. 这似乎是一个非常直接的直接回调,所以我想知道为什么在事件处理代码中显示数据时未定义数据。

     plugin = rtrn;
         console.log('4');
         plugin.dataIn(config, function(err, data) {
           if(err, data) {

             console.log('error geting data');
           } else {
            // This is where request events are being handled.  
            console.log(data);



            console.log('We are in the event handling codeblock of funtion startRuntime() located in interactor.js');

Also, here is my callback code 另外,这是我的回调代码

var ee = new events.EventEmitter();

function dataIn(config, callback) {
 if(typeof callback === 'function') {

   ee.on("dataIn", callback);

It looks like you're swallowing errors. 看来您正在吞下错误。

if(err, data) {
    console.log('error geting data');
}

That condition (err, data) will ignore the value of err . 该条件(err, data)将忽略err的值。 If data is undefined, it will be falsy and you won't know that you had an error. 如果data未定义,那将是虚假的,并且您不会知道自己有错误。 You probably want something more like this: 您可能想要更多这样的东西:

if (err) {
    console.log('error getting data')
}

Tracing back to your emitter, you are emitting in a way that sends your data to the first argument, which should be where the error goes. 追溯到发射器,您将以一种将数据发送到第一个参数的方式进行发射,第一个参数应该是错误发生的地方。 So this: 所以这:

ee.emit("dataIn", req.url);

...should be more like this: ...应该更像这样:

ee.emit("dataIn", null, req.url);

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

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