Reputation: 32130
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?
Upvotes: 4
Views: 5965
Reputation: 21089
Being 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('complete', function(response){
console.log(response);
});
};
getResp('http://google.com/');
// 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.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();
}
Once the data comes in you'll be able to pass it around like any other variable.
Upvotes: 4
Reputation: 2840
return resp;
is running before the on('complete'
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('complete', function(response){
response;
});
return result;
};
getResp('http://google.com/');
You could also use a callback like in this SO answer.
Upvotes: 1