Javascript variable not updating value [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This is makinkg me crazy, i cant Get the outside variable Get the inside data
Sorry for the bad formating I'm writing from the phone, if someone can helpme out with the format I appreciate it
window.getReasons = function(line) {
var $reasons;
$reasons = "";
$.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line, function(returnData) {
$reasons = returnData.toString();
return console.log("T_T ----->" + returnData.toString());
}, "html");
console.log($reasons);
return $reasons;
};

The most important thing for you to understand is that $.get() is ASYNCHRONOUS by default. So what is happening is that your console.log() and return statements that follow your call to get() are executing before the get() has returned it's value.
You might look to utilize the when() method here to handle the deferred object that is returned from get()
window.getReasons = function(line) {
var reasons = '';
$.when(
$.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line)
).done(function(jqxhr) {
data = jqxhr[0];
reasons = data.toString();
});
console.log(reasons);
return reasons;
}

$reasons won't be updated until after the GET completes on the server and the response is returned. But your console.log will execute immediately after the request is made.

Related

How can I obtain API response data from within a function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Javascript noob here. Apologies if there are a ton of duplicate questions out there because it seems like this must be a fundamental js function thing, but I honestly can't find an answer to this. I'm trying to wrap an API GET call in a function, and I'm running into behavior that I don't understand. The code in question:
I'm using the node-rest-client package to call the mapquest geocoding API. I'm interested in the lat/long data only.
var Client = require('node-rest-client').Client;
If I make the GET call like this, I can access parsed as an object, which is what I want.
var address = 'New York'
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
// parsed == {lat, long}
But if I wrap this in a function:
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
parsed = geocode(address);
// parsed === undefined
parsed doesn't seem to be affected by the inner function; it's undefined. How can I return parsed as an object containing the data I want as in the first example? What the heck is going on here?
In:
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
parsed = geocode(address);
// parsed === undefined
You never defined parsed outside of the scope of your function. Also you're returning parsed inside of the function before it's had a chance to retrieve from the GET request. If you wanted to do it this way, you'd need to put return(prased) inside the callback function of client.get. A better way to do it is to wrap it inside a Promise like so:
function geocode(address){
return new Promise((resolve, reject) => {
var client = new Client();
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
if(data){
resolve(data.results[0].locations[0].latLng)
}
else{
reject(response)
}
});
})
};
var address = 'New York';
var parsed;
geocode(address).then(function(latlong){
parsed = latlong
}).catch(err => {
console.log(err)});
Here, parsed will only evaluate to latlong once the Promise has been resolved (the GET request has returned successful). It will also reject the Promise if data of the GET request is NULL and return an error.
If you wanted to then do something with parsed you could include that in the .then() statement.
Learning how to code in Javascript means learning how to write code asynchronously. Promises help you treat things which are by default asynchronous as synchronous.
You never defined parsed in scope (externally to the function):
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
var parsed = geocode(address);
Notice the var parsed = geocode(address);
you need to wrap this into a promise, or return the result with callback. Callback would be like this:
function call(arg, callback) {
client.get("http:////" + arg, function (data, response) {
callback(data.results[0].locations[0].latLng)
});
}
call("yolo", function (parsed) { console.log(parsed) })
promise is well described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Javascript boolean results failing [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Why does this variable (lanFound) become undefined?
I get the following output:
Lightbulb moment! :)
As I typed the sequence of output gives it away! ajax is asynch, so the true comes back after the code has continued! I'll post anyway, might be handy for someone!
testing for: DK
result is: undefined
/sites/cspdKnowledgeAssemblyPlatform/ApprovedContent/DKCover Letter.docx succeeded
I have a set of docx files, but am adding support for languages, but to test the files (docx) have been added I use the following code (OK this is a long had variant to allow me to debug):
fileUrl = filePath + fileName;
if (lan != "EN"){
showNotification("testing for: " + lan);
var lanFound = false;
lanFound = checkURL(filePath + lan + fileName);
showNotification("result is: " + lanFound);
if(lanFound){
debugger;
fileUrl = filePath + lan + fileName;
showNotification("found " + fileUrl);
}
}
function checkURL(urlFileName){
$.get(urlFileName)
.fail(function() {
showNotification(urlFileName + " failed");
return false;
})
.done (function() {
showNotification(urlFileName + " succeeded");
return true;
});
}
You can ignore this - just added for context of "showNotification")
function showNotification(content){
var currentText = $( "#resultpanel" ).html();
currentText = currentText + "<br/>" + content;
$( "#resultpanel" ).html(currentText);
}
You cannot call an ajax call in this manner, the code will pass by before the result is returned, due to it being asynchronous, the result being the variable is read as undefined at the point at which the code passes it.
Sorry as I typed the question, I realised the answer, but posted anyway, as this might be handy for someone.

jQuery.ajax returning empty array [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm currently learning to use API's. I'm retrieving data from my Github repo. I'm trying to have the script load the JSON info into the githubData variable. But when I log the githubData variable to console it returns an empty array.
Yet, if I create a new variable with the exact same function after the page is loaded the script works exactly as it should.
When the page is loading, it's not loading the actual data. It loads an an empty array. I realize the function is asynchronous, so how would I go about getting the array to not be empty when I load the page?
Here's my code:
var githubAPI = 'https://api.github.com/repos/zacharysohovich/ticTacToe/readme';
var items = {};
jQuery.ajax({
url: githubAPI,
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
$.each(resultData, function(key,val) {
items[key] = val;
});
}
});
var githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});
The problem is that its an asynchronous call meaning that once it fires of the request it goes onto the next piece of code. Once it gets to githubData items is still an empty object because the api response hasn't been received yet.
I would instantiate the githubData variable right below var items = {}
like so
var items = {}
var githubData;
and then in the success: function after you do the $.each you can put the
githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});
this ensures that the api call has finished and items should have something in it as long as the response came back with something

Return data is not working within http request in angular [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the below function that has an http request in angular. In the success part, I am trying to return the provided data, and return the value in my setTextFile() function, but it is undefined. I have checked that data is not null or undefined, so I know it contains information, but I don't understand why it's not returning that content.
var showFile = function (txtFile, host) {
var datData;
var url = 'rest/archive-viewer/spanish-discount/' +
$rootScope.currentEnv + '/' +
host + '/' +
txtFile;
$http.get(url).success(function (data) {
$scope.sendingMessage = "Getting file";
$scope.sending = false;
$scope.sendingMessage = "";
return data;
}).error(function (data) {
$scope.sendingMessage = "Creation failed";
$scope.sending = false;
});
}
$scope.pullFiles();
};
Here is my setTextFile function who's return value is undefined as a result of the showFile() return value.
var setTextFile = function (file,host) {
console.log("Is this null " + showFile(file, host));
return showFile(file, host);
}
That http request is asynchronous. What I would suggest you to do is assigning data to a scope veriable something like : $scope.setTextFile = data in the success function you have passed in ajax request. Instead you can make a function to set the data and trigger the function inside success function.

Ajax Request wont work unless I use alert() [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've been trying for hours to get this to work, but it's just not budging; I have the following code:
var text = "";
function getText(c1, c2)
{
url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=" + c1 + "-" + c2 + "_relations&prop=revisions&rvprop=content"
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: url,
success: function (data) {
var obj = (data.query.pages );
var keys = [];
for(var k in obj) keys.push(k);
if (keys[0] == -1) {
//Link doesnt exist
text = "-1";
return text;
}
//Link Exists
else {
link = "http://en.wikipedia.org/wiki/" + c1 + "-" + c2 + "_relations"
text = c1 + "-" + c2 + " Relations"
return text;
}
}
});
return text;
}
var a = (getText(country1, country2))
alert(text);
alert(a);
I'm making an ajax request; a simple inquiry to see if wiki has a page between any 2 given countrie.
If I use alert inside, it works fine, and it returns the correct data inside the text variable. However, when the getText function is called outside, the text variable is always empty. I've tried everything I can think of, including getting the app to sleep for some time, but even that didn't work. I know the async doesn't work from ajax 1.8 onwards, but is there anyway around this?
Thanks in advance.
It is because the asynchronous behavior of ajax. You can't return values from ajax like this way. Because the function will not wait for the success event to happen.
When you put an alert inside that function, success event may occur before the user clicks on alert. That is why it returning value. Otherwise it will not return the value.
Its not a good practice to use async : false in ajax calls. It will freeze the browser.
Good practice is to call a method from the ajax success with the returned data, then do operations with that data inside the function.

Categories

Resources