This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
function getCatFact() {
var catFact = "";
request('http://catfacts-api.appspot.com/api/facts', function (error, resp, body) {
var jsonObj = JSON.parse(body);
catFact += jsonObj.facts[0];
})
console.log("HERE IT IS: "+catFact);
return "Here is your CatFact" + catFact;
}
Seems very simple but I am doing something wrong. All this function returns is Here is your CatFact.. I tried putting the return inside the request function as well, with no luck. Would love any help.
The request is asynchronous. That means that the request will fire, and JavaScript will immediately move on the the next line before the response has made it back to the client. In your case, the stuff that prints the cat fact.
Returning the cat fact itself will not work in this instance, because you will return it before the response has returned and changed the empty string. You either need to call a function within the success callback or return the request object itself.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I've been messing around with this Wikipedia node module in bash and I'm having some trouble saving the response to a variable. I can use console.log(response) to see the complete response but I can't get it to stick to a variable.
I tried maybe looking at the type of response but it just returns undefined. Any ideas?
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
});
Ideally I'd like to assign the response which has an html object to a variable and then use cheerio to get pieces of the html object with jQuery selectors, but I believe I need to at least get it in to a variable first, right?
This is part of the response.
{ title: 'Clifford Brown',
redirects: [],
text: { '*': '<div class="hatnote">For the scrutineer for the Eurovision Song Contest, see Clifford Brown (scrutineer).
Edit/Fix
I was able to get this to work based on #idbehold's comments. Everything needed to be done in the call back so instead of calling the variable after the request, I returned it in the callback like this, which gave me access to the variable outside of the function.
var wikipedia = require("node-wikipedia");
var data;
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
data = response;
})
There are many, many questions of this sort which appear on StackOverflow, and they all stem from not understanding the asynchronous nature of AJAX. Your code does not block at the .data() call to wait for the server to respond. Any lines of code that run after that call will run immediately, whereas the code inside your callback function will runs at some point in the future, after the data is returned from the server. Anything you do in response to getting the data must happen in that callback.
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
// do something with the response here
});
// any code here will run before the above callback is invoked.
// don't try to do anything with the response here.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I have a following piece of javaScript code:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path); //alert 1
},
'text');
alert(ws_path); // alert 2
// output = alert 1 = value of data
// alert 2 = x
I have a confusion' why it is behaving like this?
It is because alert(ws_path); gets executed before the content is get from server for ws.config file. You need to write the code in success function of get to ensure that variable is modified after get request.
jQuery.get
The second alert is fired before the $.get request is completed.
The important point here is:
$.get('ws.config' ....
is a kind of ajax call and it takes some time to get the actual value from the server, and that anonymous function there is a callback function which gets called when the ajax call receives the response.
Here in your code if you want to have a ordered scenario you can do this:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path);
continueScenario();
}, 'text');
function continueScenario(){
alert(ws_path);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
This the data im getting from post is a simple object and the return value is always empty. Its logging to the console fine. any ideas?
function getTaskData(item){
var returnText = '';
$.post("index.php", {name: "getTaskData", pk: item.taskDataId}, function(data){
console.log(data);///Object {taskData: "Also - whats up with this?"}
console.log(data.taskData);///Also - whats up with this?
returnText = data.taskData;
},"json");
return returnText;
}
The code included in the block function(data) { ... is called a callback. It will be aynchronously called when the server's ajax call has finished. Whereas the return returnText will be called immediately.
Whatever you are going to do with the returntext (update DOM etc) will need to be done in the callback function
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I want to load a data that I got from Jquery.get into the variable in another function. The way I have tried is
function setPolicy(){
jQuery.get('/webapp/myProject/getPolicy', function(policy) {
console.log(policy + " Policy"); //Just for Observation
}); }
and I want to load the data which is now stored in the Parameter Name "policy" into another variable in another function like the following
function loadAPI() {
var policy = setPolicy();
console.log("The policy is " + policy);
The result Shows in the console is just
The policy is
which mean the variable policy is not receive the data from the function.
What I would like to ask is How can I load the data from function "setPolicy" into the variable Name "policy" in another function calls "loadAPI" as a string? Thank you in advance.
You need to return the fetched value. Try to add this stmt in your code -
$.get('URL', function(data) {
$('.result').html(data);
return data;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am creating an object in javascript:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
});
alert(t);
When I alert data, I get an object back.
When I alert t, it's null.
Can you please guide, how to set "t" to the returned data?
This will work as expected - the issue is not that t is not set, it's that you're doing alert(t) before the getJSON callback is executed. Try doing alert(t) immediately after t = data;
In other words, here's your current order of operations:
Set t = null
Call server script
alert(t) --> t is still null!
(some amount of time later) receive JSON response
alert data
set t = data
...as you can see, at step 3 't' will still be null. Try this instead:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
alert(t);
});
Cheers