gpt4 book ai didi

javascript - 了解发射函数 esp 的 Node.js 代码

转载 作者:行者123 更新时间:2023-12-02 15:21:26 25 4
gpt4 key购买 nike

我正在努力完全掌握下面的代码。我想了解 emit 的工作原理。

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

  1. profileEmitter.emit("error", new Error("获取 "+ 用户名 + "的配置文件时出错。("+ http.STATUS_CODES[response.statusCode] + ")"));

它执行错误函数。(但我不确定错误函数在代码中定义的位置。

  • response.on('数据', 函数 ( block ) {
    主体 += block ;
    profileEmitter.emit(“数据”, block );
    });
  • 这会发出上面定义的数据事件函数。一切都很好!但第二个参数是什么。根据文档,这个参数应该是一个监听器,但它只是一个在数据之前定义的“匿名函数”的参数。

  • 尝试{
    //解析数据
    var profile = JSON.parse(body);
    profileEmitter.emit("结束", 配置文件);
    } 捕获(错误){
    profileEmitter.emit("错误", 错误);
    }
  • 这次 try block 中的第一个发出有一个 profile 变量。catch block 中的第二个发出有一个 error 作为第二个参数。出色地 !都一头雾水。

    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 事件以及刚刚接收到的数据 block 。

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

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

    关于javascript - 了解发射函数 esp 的 Node.js 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015719/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com