为什么我的节点事件回调在事件中显示为未定义? [英] Why is my node event callback showing up in the event as undefined?

查看:135
本文介绍了为什么我的节点事件回调在事件中显示为未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将url字符串作为data传回我的eventhandler。

I am trying to pass back a url string as "data" into my eventhandler.

我对服务器的请求是 https://172.20 .10.6 / index.html的
下面的 console.log 按照我的预期打印出/index.html。

My request to the server is "https://172.20.10.6/index.html". The console.log below prints out "/index.html" as I expect.

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

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

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

     break;

以下是eventHandler代码。

控制台.log(data); 计算为undefined。我想弄清楚为什么会这样。这似乎是一个非常简单的直接回调,所以我想知道为什么数据在事件处理代码中显示时没有定义。

Below is the eventHandler code.
The 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');
}

该条件(错误,数据)将忽略<$ c的值$ c>错误。如果数据未定义,它将是假的,你不会知道你有错误。你可能想要更像这样的东西:

That condition (err, data) will ignore the value of err. If data is undefined, it will be falsy and you won't know that you had an error. 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);

这篇关于为什么我的节点事件回调在事件中显示为未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆