我正在努力获得下面的代码的完整信息。我想了解emit的工作原理。

这是我对以下代码中提到的所有发射实例的理解。


profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));


它执行错误功能。(但我不确定代码中错误功能的位置。


response.on('data', function (chunk) { body += chunk; profileEmitter.emit("data", chunk); });


发出上面定义的数据事件函数。但是第二个参数是什么。根据文档,此参数应该是一个侦听器,但是所有它都是在数据之前定义的“匿名函数”的参数。


try { //Parse the data var profile = JSON.parse(body); profileEmitter.emit("end", profile); } catch (error) { profileEmitter.emit("error", error); }


这次try块中的第一个发射具有profile变量。
catch块中的第二个发射具有error作为第二个arg。好 !一切困惑。

var EventEmitter = require("events").EventEmitter;
var http = require("http");
var util = require("util");


function Profile(username) {

EventEmitter.call(this);

profileEmitter = this;

//Connect to the API URL (http://teamtreehouse.com/username.json)
var request = http.get("http://example.com/" + username + ".json", function(response) {
    var body = "";

    if (response.statusCode !== 200) {
        request.abort();
        //Status Code Error
        profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
    }

    //Read the data
    response.on('data', function (chunk) {
        body += chunk;
        profileEmitter.emit("data", chunk);
    });

    response.on('end', function () {
        if(response.statusCode === 200) {
            try {
                //Parse the data
                var profile = JSON.parse(body);
                profileEmitter.emit("end", profile);
            } catch (error) {
                profileEmitter.emit("error", error);
            }
        }
    }).on("error", function(error){
        profileEmitter.emit("error", error);
    });
});
}

util.inherits( Profile, EventEmitter );

module.exports = Profile;

最佳答案

EventEmitter.emit()函数正好说出了它的意思:它将事件发送给已为该事件注册的侦听器。

第一个参数(事件类型)之后的参数仅是事件的参数,它们不是侦听器。

因此,您的第一个调用只是发送一个error事件,带有附加的Error参数来描述错误。

第二个调用发送一个data事件以及刚刚接收到的数据块。

第三次调用发送end事件以及已解码的配置文件。

最后一个调用发送一个error事件,以及从catch收到的错误。

09-25 18:15
查看更多