I have a function that I am trying to pass a string out of to create a new variable - see below:
function networks(networkGroupId) {
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push( countryList.code + ": 'NORTH AMERICA'")
});
var regionListOutput = '{' + regionList + '}';
console.log(regionListOutput);
}
});
};
var networkList = networks('15001');
console.log('Network List = ' + networkList);
The problem I have is that when I run this I get a console output of
Network List = undefined
{AG: 'NORTH AMERICA',AI: 'NORTH AMERICA',AR: 'NORTH AMERICA',AW: 'NORTH AMERICA',BB: 'NORTH AMERICA',BM: 'NORTH AMERICA',BO: 'NORTH AMERICA',BR: 'NORTH AMERICA',CL: 'NORTH AMERICA',CO: 'NORTH AMERICA',CR: 'NORTH AMERICA',CW: 'NORTH AMERICA',DM: 'NORTH AMERICA',DO: 'NORTH AMERICA',EC: 'NORTH AMERICA',GD: 'NORTH AMERICA',GF: 'NORTH AMERICA',GT: 'NORTH AMERICA',HT: 'NORTH AMERICA',JM: 'NORTH AMERICA',KN: 'NORTH AMERICA',KY: 'NORTH AMERICA',LC: 'NORTH AMERICA',PA: 'NORTH AMERICA',PE: 'NORTH AMERICA',PY: 'NORTH AMERICA',TC: 'NORTH AMERICA',TT: 'NORTH AMERICA',UY: 'NORTH AMERICA',VC: 'NORTH AMERICA',VE: 'NORTH AMERICA',VG: 'NORTH AMERICA',MQ: 'NORTH AMERICA',GP: 'NORTH AMERICA',SV: 'NORTH AMERICA',HN: 'NORTH AMERICA',NI: 'NORTH AMERICA',BS: 'NORTH AMERICA',BZ: 'NORTH AMERICA',GY: 'NORTH AMERICA',MF: 'NORTH AMERICA',MS: 'NORTH AMERICA',SR: 'NORTH AMERICA',BQ: 'NORTH AMERICA',BL: 'NORTH AMERICA',SX: 'NORTH AMERICA'}
When I actually want both logs to be the string {...}
I think I understand that networkList is returning as undefined because it is not waiting for the result of networks('15001') but I don't know how to go about correcting this. Can anybody help?
EDIT
To further add some clarification, after setting the variable of networkList to be the string {AG: 'NORTH AMERICA',AI: 'NORTH AMERICA'...} I then want to pass it to the variable regionStyling see below (the console logs are just for me to check that the correct string is being passed):
function networks(networkGroupId, callback) {
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push(countryList.code + ": 'NORTH AMERICA'")
});
var regionListOutput = '{' + regionList + '}';
console.log(regionListOutput);
callback(regionListOutput);
}
});
};
var networkList = [];
networks('15001', function (regionListGottenFromTheNetworksFunction) {
networkList = regionListGottenFromTheNetworksFunction;
console.log('Network List = ' + networkList);
});
console.log(networkList);
var regionStyling = {
regions: [{
values: networkList //this should be the string {AG: 'NORTH AMERICA',AI:...}
, scale: {
"NORTH AMERICA": "#2761ad"
, "EUROPE": "#d58aa3"
, "ASIA": "#ee549f"
, "LATIN AMERICA": "#15bbba"
, "AFRICA & MIDDLE EAST": "#8864ab"
}
}]
};`
1 Answer 1
Welcome to the asynchronous world!
First, you're not returning anything inside of your method. Then, what's happening inside the method is asynchronous, it means it might take a while based on many things, on the other hand the following lines are one after the other:
var networkList = networks('15001');
console.log('Network List = ' + networkList);
So meanwhile these two lines are being executed right away, maybe the AJAX paart hasn't been executed completely, therefore there would be no values being returned.
There are two things you can do:
1 - Use Callbacks
A callback function is executed after the current effect is finished.
function networks(networkGroupId, callback) {
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
var regionListOutput = '{';
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push( countryList.code + ": 'NORTH AMERICA'");
regionListOutput += countryList.code + ":'NORTH AMERICA',";
});
regionListOutput = regionListOutput.replace(/,\s*$/, ""); //Remove last comma
regionListOutput += "}";
callback(regionListOutput);
}
});
};
var networkList = [];
networks('15001', function(regionListString){
networkList = regionListString;
console.log('Network List = ' + networkList);
});
2 Use Promises (I prefer this over callbacks)
So once things get really interesting and you're still using callbacks you could easily go into a Callback hell
function networks(networkGroupId, callback) {
return new Promise(function(resolve, reject){
jQuery.ajax({
type: 'GET'
, url: apiURL + 'api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
, dataType: 'json'
, success: function (networkGroup) {
var regionList = []; // temporary array
var regionListOutput = '{';
jQuery.each(networkGroup.countryList, function (i, countryList) {
regionList.push( countryList.code + ": 'NORTH AMERICA'");
regionListOutput += countryList.code + ":'NORTH AMERICA',";
});
regionListOutput = regionListOutput.replace(/,\s*$/, ""); //Remove last comma
regionListOutput += "}";
resolve(regionListOutput);
}
});
})
};
var networkList;
networks('15001').then(function(regionListString){
networkList = regionListString;
})
Leaving the async part aside, what you're trying to achieve here doesn't actually make much sense:
var regionListOutput = '{' + regionList + '}';
since you're concatenating strings and an array. What you need to do is do this concatenate part within the foreach loop you already have. I edited both approachs.
Here's a JS Fiddle you can test. https://jsfiddle.net/ggderas/67f7p2rb/1/
4 Comments
{AG: 'NORTH AMERICA',AI: 'NORTH AMERICA'...} I want this variable to be that string so I can then use it as a variable in another function.{AG: 'NORTH AMERICA',AI: 'NORTH AMERICA'...} . See my edit to the original post. and thanks for your help.Explore related questions
See similar questions with these tags.
networksdoes not have areturnstatement, thus the return value of the function is alwaysundefined.