This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed last year.
I am storing the data from an API call in variables and I would like to use the data in the variables elsewhere in the function. However, when I printout what is in the variables outside of the arrow function, the data has a type of undefined.
The first console.log(coordinates); displays ["08002", "39.916258", "-75.021428"] and the second displays
[
"08002",
"39.916258",
"-75.021428"
]
But when I have console.log(coordinates[1]); outside of the arrow function it says it's undefined.
const getLongLat = function(zip) { //gets long lat from a zip code
zip = document.getElementById("ZipCode").value
let lat = 0;
let long = 0;
let coordinates = [];
if (zip == "") {
zip = "08002"
}
coordinates.push(zip);
const APIkey = "#########";
let base = `http://open.mapquestapi.com/geocoding/v1/address?
key=${APIkey}&location=${zip}`;
console.log("base " + base);
fetch(base)
.then(response => response.json())
.then(data => {
//makes it so that the city is in the us
let i = 0;
while (data.results[0].locations[i].adminArea1 != "US") {
i++
}
lat = String(data.results[0].locations[i].latLng.lat);
long = String(data.results[0].locations[i].latLng.lng);
coordinates.push(lat);
coordinates.push(long);
console.log(coordinates);
})
console.log(coordinates);
return coordinates;
};
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 1 year ago.
What I am trying to achieve here is to build a chart with the average SLA for each of the 4 regions. For this, I am calling an API to get some ids, I use these ids to call another API and get the SLAs. Then, I'm calculating the average SLA. I have to do this 4 times for each region. In the end, I want to have 2 arrays containing the region names and the average SLAs, so I can build the chart. Problem is, I can't get the SLA data out of these nested functions, so I can build the array. It tells me that the variables are undefined.
So the question is why can't I access the average var as soon as I leave the function? I tried using return average;. I also tried returning from both function(response) and function(data). This is the first JS I write and I feel like there is something very wrong with it. Can you help me find out what?
// This is the fetch that gets me the SLAs and where I calculate the averages.
function regionsla(serviceids, regionName) {
fetch('api.php', {
// request body
}).then(
function(response) {
response.json().then(
function(data) {
var i = 0;
var sum = 0;
var labels = [];
var values = [];
for (const label in data.result) {
sum = sum + data.result[label].sla[0].sla;
i++;
}
average = sum / i;
labels.push(regionName);
values.push(average);
}
)
}
);
}
// This is the main function that runs in the beginning. The fetch is inside a for loop and it will get me the IDs that I need in order to run function regionsla.
async function get_sla() {
regionsids = [58, 59, 60, 61];
americaids = [];
europeids = [];
asiaids = [];
australiaids = [];
for (const regionid of regionsids) {
fetch('api.php', {
// request body
}).then(
function(response) {
response.json().then(
function(data) {
for (const label in data.result) {
switch (regionid) {
case 58:
americaids.push(data.result[label].serviceid);
break;
case 59:
australiaids.push(data.result[label].serviceid);
break;
case 60:
asiaids.push(data.result[label].serviceid);
break;
case 61:
europeids.push(data.result[label].serviceid);
}
}
switch (regionid) {
case 58:
regionsla(americaids, "America");
averageAmerica = average;
console.log(averageAmerica); //this returns
break; // average is not defined
case 59:
regionsla(australiaids, "Australia");
break;
case 60:
regionsla(asiaids, "Asia");
break;
case 61:
regionsla(europeids, "Europe");
}
})
}
);
}
}
The problem is with the scope of variables. Variables will be accessible only within the function they are declared. If you want to access the variable globally, declare it globally. May i know where is the Average variable declared?
As discussed in the comments following code will give you some ideas.
function showName() {
var result;`enter code here`
result = addString('Hello', ' World');
document.write (result );
}
// in below we will check how to return string from function
function addString(fName, lName) {
var val;
val = fName + lName;
return val; // returning string from function
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
My console.log shows the right values, but I can't access my properties!
var subMenus = [], mainMenu = {};
$.getJSON("js/menu.js", function(data){
var menuJsonish = data.MenuEXTERNAL;
//first turn this into an actual array instead of this dumb, non Json stuff
$.each(menuJsonish, function(e) {
var name = e.valueOf();
var eachMenu = [];
if (e != "MenuSettings") { //skip MenuSettings
$.each(menuJsonish[name], function(element) {
var menuArray = [];
$.each(menuJsonish[name][element], function(item) {
var currentItem = menuJsonish[name][element][item];
var k = currentItem[0].valueOf();;
var v = currentItem[1].valueOf();
if (e == 'Menu1') {
eval("mainMenu."+k+" = '"+v+"'");
} else {
eachMenu[k] = v;
}
});
});
if (e != 'Menu1') {
subMenus[e] = eachMenu;
}
}
});
});
// this one returns undefined...
console.log(mainMenu.Menu1);
// yet this one returns all the correct data as shown in the screenshot
console.log(mainMenu);
I don't understand what is going on here. Shouldn't a value be a value? And more importantly, how do I get my data?
I don't think it's necessary to post the entire "JSON" file (which I did NOT create, but I have to work with), but I will post screenshot #2 which shows what it looks like, and why I have to load it like this.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I declared a variable names with an empty array value out of the function, then used it inside the function to assign returned value, then I want to use it outside this function, but outside the function this variable remains empty.
Please explain what I'm doing wrong.
handleUpdateInputBusinessName = (searchText) => {
var names = [];
var displaySuggestions = function(predictions, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach(function(prediction) {
let name = prediction.description;
names.push(name);
});
console.log('names_in:', names); // valid predictions from Google Maps Service
return names;
};
console.log('names_out:', names); // []
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: searchText, types: '(cities)'
}, displaySuggestions);
Here's the boiled down version:
a = [];
var b = () => {
a.push(1);
console.log('inside:', a)
};
console.log('outside:', a);
b();
The "outside" console log is running before the displaySuggestions function is called, so the data is not yet populated in the array.
you have to use js anonymous function syntax to increse the scope of names array below is the code.
handleUpdateInputBusinessName = (searchText) => {
var names = [];
var displaySuggestions = (predictions, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach((prediction) => {
let name = prediction.description;
names.push(name);
});
console.log('names_in:', names); // valid predictions from Google Maps Service
return names;
};
console.log('names_out:', names); // []
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: searchText, types: '(cities)'
}, displaySuggestions);
hope this heps.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a function which is a loop by itself and in this loop I am creating an object. But when after the loop I'm trying to access the object properties, I get an response of undefined.
When I try to just console.log the object itself, I get it. The problem is with properties.
I would be grateful, if someone could help me. I did a good research, but didn't manage to find the solution. My case is very strange. Everything is good except the properties. I need the help of senior developers.
Here is the code.
var countMap = {};
var counter = 0;
$('#share_table_body').find('.js-post').each(function () {
var totalCount = 0;
$(this).find('.js-social').each(function () {
var $this = $(this);
var socialType = $(this).data('social-type');
var url = $this.closest('.js-post').data('url');
getShareStatus(url, socialType)
.then(function (shareCount) {
$this.text(shareCount);
if (!countMap[socialType]) {
countMap[socialType] = 0;
}
if (!countMap['total']) {
countMap['total'] = 0;
}
countMap[socialType] += shareCount;
totalCount += shareCount;
countMap['total'] += shareCount;
$this.siblings('.js-total').text(totalCount);
})
.fail(function (err) {
$('.error-notice').removeClass('hidden');
$this.css('color', 'red').text('!');
});
});
counter++;
});
if (counter == $('#share_table_body').find('.js-post').length) {
console.log(countMap);
$('.total-facebook').text(countMap['facebook']);
}
Are you returning anything from your function? Specifically...
return countMap;
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm trying to build a function that stores an array of JS objects in a global scope (I want to access this from an external Prototype function). However, when I try to return the 'build' array, the array is undefined (this is probally because I need a proper callback function).
How can I achieve this in a proper way?
function getMyJson(url){
var request = $.getJSON(url);
var items = [];
request.done(function(response) {
for (var key in response) {
if (response.hasOwnProperty(key)) {
var object = {
name: response[key].name,
id: response[key].id
}
items.push(object);
}
}
});
return items; // This returns 'undefined', probally because the for loop is still running
}
var data = getMyJson('data.json');
console.log(data); // undefined
Thanks in advance
As others have mentioned, callbacks are the way to go.
function getMyJson(url, callback){
var request = $.getJSON(url);
var items = [];
request.done(function(response) {
for (var key in response) {
if (response.hasOwnProperty(key)) {
var object = {
name: response[key].name,
id: response[key].id
}
items.push(object);
}
}
callback(items);
});
}
var data = getMyJson('data.json', function(items){
//items will be defined here.
});