节点js restler结果“获取"尝试返回结果时未完成 [英] node js restler result "get" not complete when trying to return result
问题描述
我正在尝试使用Restler获取网站的HTML.但是,当我尝试获取结果的相关部分时,总是会出现错误,
I'm trying to get the HTML of a website using restler. But when I try to get the relevant part of result, I always get the error,
"TypeError:无法读取未定义的属性'rawEncoded'".
"TypeError: Cannot read property 'rawEncoded' of undefined".
"rawEncoded"有时是"res".我认为它会根据处理时间而变化.
'rawEncoded' sometimes is 'res'. I think it changes based on processing time.
我正在尝试从restler获取result.request.res.rawEncode来获取结果.
I'm trying to get result.request.res.rawEncode from restler get result.
我的功能:
var rest = require('restler');
var loadHtmlUrl = function(weburl) {
var resultstr = rest.get(weburl).on('complete', function(result) {
var string = result.request.res.rawEncode;
return string;
});
return resultstr;
};
然后:
var htmlstring = loadHtmlUrl('http://google.com');
也许restler是完全错误的方法.也许我不太了解.但是我肯定被困住了...
Maybe restler is the entirely wrong way to go. Maybe I don't understand it completely. But I'm definitely stuck...
谢谢!
推荐答案
在调用on('complete'
回调之前,您的return resultstr;
是否不会运行,因为它是异步的,因此导致您的htmlstring
为空吗?我认为您需要像这样将loadHtmlUrl
的参数作为回调:
Would your return resultstr;
not run before the on('complete'
callback gets called because it is asynchronous, therefore resulting in your htmlstring
being null? I think you need to have a callback as a parameter to your loadHtmlUrl
like so:
var rest = require('restler');
var loadHtmlUrl = function(weburl, callback) {
var resultstr = rest.get(weburl).on('complete', function(result) {
callback(result.request.res.rawEncode);
});
};
然后这样称呼它:
var htmlstring = null;
loadHtmlUrl('http://google.com', function(rawEncode) {
htmlstring = rawEncode;
//Do your stuff here...
});
我认为这将解决您将来遇到的问题.但是,我认为您面临的真正问题是result.request没有res
属性.我在想我的上述更改可能会解决此问题(不太确定如何解决).如果没有,那么我建议您查看result.request
具有哪些属性作为调试入门...
I think that will resolve future problems you will have. However, I think the real problem you're facing is that result.request does not have the property of res
. I'm thinking that my change above may fix this problem (not quite sure how). If not, then I would recommend looking at what properties result.request
has as a debugging starter...
这篇关于节点js restler结果“获取"尝试返回结果时未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!