node js restler result “get” not complete when trying to return result

折月煮酒 提交于 2019-12-12 01:22:50

问题


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: Cannot read property 'rawEncoded' of undefined".

'rawEncoded' sometimes is 'res'. I think it changes based on processing time.

I'm trying to get result.request.res.rawEncode from restler get result.

My function:

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;
};

Then:

var htmlstring = loadHtmlUrl('http://google.com');

Maybe restler is the entirely wrong way to go. Maybe I don't understand it completely. But I'm definitely stuck...

Thanks!


回答1:


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);
    });
};

And then call it like so:

var htmlstring = null;
loadHtmlUrl('http://google.com', function(rawEncode) {
  htmlstring = rawEncode;
  //Do your stuff here...
});

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...



来源:https://stackoverflow.com/questions/17559378/node-js-restler-result-get-not-complete-when-trying-to-return-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!