4

I don't understand why this code doesn't work for me

var rest = require('restler');

var getResp = function(url){
        var resp ="";
        rest.get(url).on('complete',function(response){
          resp = response.toString();
        });
        return resp;
    };

I am not getting the response for getResp('google.com')

Am I missing something with restler?

4

2 回答 2

4

由于您要返回resp,因此您似乎忘记了请求是异步的。而是试试这个:

var rest = require('restler');

var getResp = function(url){
  rest.get(url).on('complete', function(response){
    console.log(response);
  });
};

getResp('http://google.com/');

// output:
// <!doctype html><html itemscope="itemscope" ....

由于它的异步特性,最好将值传递给接收回调。举个小例子:

var rest = require('restler');

// process an array of URLs
['http://google.com/',
'http://facebook.com/'].forEach(function(item) {
  getResp(item);
});

function getResp(url){
  rest.get(url).on('complete', function(response){
    processResponse(response);
  });
};

// data will be a Buffer
function processResponse(data) {
  // converting Buffers to strings is expensive, so I prefer
  // to do it explicitely when required
  var str = data.toString();
}

一旦数据进来,你就可以像任何其他变量一样传递它。

于 2013-07-10T07:22:28.950 回答
1

return resp;在回调被调用之前运行,on('complete'因为它是异步的。这导致resp变量永远不会被赋值。

尝试这个:

var rest = require('restler');

var getResp = function(url){
  var result = rest.get(url).on('complete', function(response){
   response;
  });
  return result;
};

getResp('http://google.com/');

您也可以像在这个 SO answer中那样使用回调。

于 2013-07-10T07:33:09.447 回答