Getting HTTP Response using restler in Node.js - javascript

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?

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.

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.

Related

Use the data from 1st JSON and convert it to a variable and use that variable to call a 2nd JSON

I am new here but I have a problem and need your help, so in my code I called a JSON file.
var data = {};
var spectator;
var tmp = [];
var IDcatcher =[];
var summonerID = [];
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
});
so this gives me the ID from the JSON which is stored in summonerID variable now I want to use this variable to complete the URL to get the 2nd JSON so.
var spectatorUrl = "link" + summonerID;
Now get the 2nd JSON
var Charcatcher =[];
var CharID = [];
$.getJSON(spectatorUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (Charcatcher in tmp) {}
});
CharID = tmp[Charcatcher].id;
});
My problem is the 2nd JSON doesn't run, it doesn't get anything and returns nothing (obviously).
Help?
I can't run 2 JSONs at different times? If so how can I do it or change it?
As I mentioned, due to the asynchronous nature of JavaScript, if you have an AJAX request with a callback and some code following the request, JS will fire off the AJAX request and will continue with the rest of the code. It won't wait for the result of the AJAX request to return.
Here's a simple demo -
function first() {
setTimeout(() => {
console.log("1");
}, 2000);
console.log("2");
};
first();
Look at the order of the console.log statements in the code, and then check the actual order in the console.
To solve your original problem, you can nest a $.getJSON() inside the first one, this will ensure that summonerID is available when you fire off the second AJAX request.
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
// second AJAX request
var spectatorUrl = "link" + summonerID;
$.getJSON(spectatorUrl, function(data) {
// logic
});
});

Function needs to return Rest Call response as JSON object. How to set the response to a variable so that it can be return as variable

var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
console.log(JSON.parse(data));
messageData=data;
});
//how to set the response of that rest call to this messageData object
return messageData;
}
}
this method getWeatherStatus should return the rest response in json format.
Open for totally different suggestion to implement this kind of scenario.
My basic requirement is to use this REST call response and send to other functions.
In getWeatherStatus you use async function client.get. You need wait result from async function and only than return messageData. For this you can use deasync. Example:
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
console.log(JSON.parse(data));
messageData=data;
});
//We waiting for data.
while (messageData === "") {
require('deasync').sleep(10);
}
return messageData;
}
}
But, maybe, you should return Promise, not data.
Since get is callback function so you have to put your return messageData
in stead of messageData=data.
Code should be like
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
return JSON.parse(data);
});
}
}
I think you are facing difficulties to deal with with callbacks,
In the method getWeatherStatus, instead of returning the result, you should pass it to a callback function once the treatment is done.
If really you are required to return, galk.in answer seems to be a possible way.
Otherwise, check this out,
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function(then) {
var messageData = "";
client.get("/some/url", function (data, response) {
then(err=null, JSON.parse(data));
});
}
}
So you may call getWeatherStatus in such way,
// Somewhere else in your code
getWeatherStatus(function fnCallback(err, jsonData) {
console.log(jsonData) // process data here
})
As suggested, Promise are also a good alternative. but it is still async.

Cannot catch the output of an asynchronous callback into a variable in JavaScript

My code block goes like this :
var http = require("http");
function get_json(url,callback) {
var response = '';
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
response = JSON.parse(body);
callback(response);
});
});
}
// -----------the url---v ------------the callback---v
var mydata = get_json("http://alfreddelivery.cloudapp.net/api/questionnaire/",function fn(item){
console.log(item);
});
I would like to catch the output of get_json function and then assign it to a variable for future options. I tried, var mydata to access the JSON object parsed, but, since the program execution flow hits the mydata variable first, it returns, undefined value for the variable. I have reused this code from stack overflow itself. Please help me for
returning the JSON object to a variable from the async callback in get_json
Use this code base in a JS file and reference it in a web application.
Thanks in advance.

Is there a canonical pattern for implementing self-memorizing function in JavaScript?

I need to implement a simple cache in JavaScript for storing results of ajax requests. I know that one of the way is to implement self-memorizing function. But is there some general pattern for this in JavaScript, without using any frameworks?
var getAjax = (function(params){
var cache = {};
var paramsToURLKey = function(params){
return paramsConvertedToString; // convert params object to string and use it as key for cache
};
getAjax = function (params, callback) {
var key = paramsToURLKey(params);
var result = cache[key]; // try to read previous request results
if (!result) {
sendRealRequest(params, function(response){
//request callback
cache[key] = response;
callback(response);
})
}
}
})();

How to use YAHOO.util.Connect.asyncRequest and return results?

I'm using YAHOO.util.Connect.asyncRequest to get data from database, here is the code :
function getCountArticle(contentCurValue) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
alert(contentCountPubmed); //return 15 for example
};
var handleFailure = function () {
alert("Error connecting data : Bad pubmed query");
};
var callback =
{
success:handleSuccess,
failure:handleFailure,
timeout: 5000
};
var sURL = 'qct-list-article.html?term=' + contentCurValue + '&retstart=0' + '&retmax=1';
var request = YAHOO.util.Connect.asyncRequest('GET',sURL,callback);
}
I would like this function return : "contentCurValue" (eg:15), but when I try to use this code I get "undefined" :
var test = getCountArticle();
alert(test); // return undefined, should return 15
My error is probably due to asynchronous query, but how can I force "var test = getCountArticle();" to wait for results ?
Since the call is by nature asynchronous, rather than try to wait for the response, you would be better off specifying a callback function to execute with the data. You could modify your method like this:
function getCountArticle(contentCurValue, callback) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
callback(contentCountPubmed); //return 15 for example
};
// ...
}
then your calling code would be:
getCountArticle("contentCurValue", function(test) {
alert(test);
});
Any further execution using the value returned from your AJAX query would proceed inside of your callback method.
This SO post is essentially the same problem, but not YUI specific: Getting undefined in javascript when calling ajax

Categories

Resources