0

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
  • 1
    Your function networks does not have a return statement, thus the return value of the function is always undefined. Commented Aug 1, 2017 at 22:54

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

4 Comments

While using the callbacks method works for the console.log, it still doesn't set the variable of networkList to be the string {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.
@JodySergison check the callback approach again, there's an edition on the answer
this still does not set the ariable of networkList to be the string {AG: 'NORTH AMERICA',AI: 'NORTH AMERICA'...} . See my edit to the original post. and thanks for your help.
@JodySergison I think I finally understood what you were saying, you can check the edited answer and also a JS Fiddle for better understanding. I didn't use JQuery's foreach, I used ES6 instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.