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('plete',function(response){
resp = response.toString();
});
return resp;
};
I am not getting the response for getResp('google')
Am I missing something with restler?
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('plete',function(response){
resp = response.toString();
});
return resp;
};
I am not getting the response for getResp('google.')
Am I missing something with restler?
Share Improve this question asked Jul 10, 2013 at 6:57 Nick GinantoNick Ginanto 32.2k49 gold badges141 silver badges250 bronze badges 2-
did you try
getResp('http://google.')
? – Scott Bartell Commented Jul 10, 2013 at 7:13 -
something thing.. I get
''
– Nick Ginanto Commented Jul 10, 2013 at 7:14
2 Answers
Reset to default 4Being that you're returning resp
it looks like you've forgotten that the request is asynchronous. Instead try out this:
var rest = require('restler');
var getResp = function(url){
rest.get(url).on('plete', function(response){
console.log(response);
});
};
getResp('http://google./');
// output:
// <!doctype html><html itemscope="itemscope" ....
Because of its asynchronous nature it's preferred that you pass the value to a receiving callback. Take this small example:
var rest = require('restler');
// process an array of URLs
['http://google./',
'http://facebook./'].forEach(function(item) {
getResp(item);
});
function getResp(url){
rest.get(url).on('plete', 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();
}
Once the data es in you'll be able to pass it around like any other variable.
return resp;
is running before the on('plete'
callback gets called because it is asynchronous. This is resulting is the resp
variable never getting assigned a value.
Try this:
var rest = require('restler');
var getResp = function(url){
var result = rest.get(url).on('plete', function(response){
response;
});
return result;
};
getResp('http://google./');
You could also use a callback like in this SO answer.