这有什么不对吗?尝试在原型中使用请求回调,但收效甚微

What is wrong with this? Trying to use request callback in a prototype...with little success

本文关键字:请求 回调 收效甚微 原型 什么      更新时间:2023-09-26

这个要点是我如何尝试包含一个回调请求,以使用Node.js与request和Cheerio从一系列网页中提取一些元素。最初,我的基本逻辑只使用了一个函数。然而,我试图让它更面向对象,显然失败得很惨。既然这个逻辑以前有效,我完全不明白为什么现在不起作用了。

事先感谢您的帮助。

要点:https://gist.github.com/knu2xs/5acc6f24c5df1c881cf7

你的一个问题在这里,第82行:

if (!error) {
    var $ = cheerio.load(body);
    // get properties from the html
    this.name_river.get($);
    this.name_reach.get($);
    this.difficulty.get($);
    this.length.get($);
}

内部回调函数没有绑定到相同的作用域,所以this不是Reach的实例。

你需要获取一个引用并使用它:

function Reach(reach_id) {
    /* ...  */
    var self = this;
    this.request = request(url_root + this.reach_id, function (error, response, body) {
        /* ...  */
        self.name_river.get($);
        /* ...  */
    });
}

…或者显式地将它绑定到:

function Reach(reach_id) {
    /* ...  */
    this.request = request(url_root + this.reach_id, (function (error, response, body) {
        /* ...  */
        this.name_river.get($);
        /* ...  */
    }).bind(this));
}

关于this的MDN文章https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


另一个问题是这里的调用,第104行:
reach.request();

请求没有被设置为一个函数,如果我没看错的话。第79行在实例创建期间执行请求:

this.request = request(url_root + this.reach_id, function (error, response, body) {