这有什么不对吗?尝试在原型中使用请求回调,但收效甚微
What is wrong with this? Trying to use request callback in a prototype...with little success
这个要点是我如何尝试包含一个回调请求,以使用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) {
相关文章:
- 成功回调永远不会被JSONP请求调用
- PJAX请求完成并下载资产后的回调
- google在类内映射javascript directionsService.route请求:将类实例传递给回调函数
- 如何在回调请求中传递var
- 请求js中的回调问题
- JavaScriptajax请求servlet调用错误回调函数
- Google Maps JavaScript API v3:getDetails(请求,回调),用于多个位置
- 节点 js 将变量传递到请求回调函数中
- 带有一个回调的多个循环ajax请求
- 如何从ajax get请求的回调函数中编辑javascript变量的值
- jQuery中的多个同时Ajax请求(带有一个回调)
- jQuery,在任何请求之前对 ajax 请求的默认回调
- Jquery jsonp 请求回调函数未触发
- node . js Http.请求回调-无法将数据传递给父函数
- 突然,我的IndexedDB打开请求回调都没有被调用
- 向请求回调添加额外的参数
- http.Get或http.请求回调只显示在shell - node.js中
- 异步angularJS -如何等待每个请求回调
- 这有什么不对吗?尝试在原型中使用请求回调,但收效甚微
- HTTP请求回调未执行-原因