0

I'm new to javascript and its callback function, I got this super simple script where I created a function, within it, I used jQuery.getJSON to retrieve some JSON data, then return the target value, when I ran this script, I can't get the expected output, how should I call a javascript callback function?

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='X-UA-Compatible' content='IE=edge' />
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <script defer="true">
    var parseSheet = function(url) {
        var output = "";
        $.getJSON(url, function(data) {
            output = data.version;
            console.log(output); // this will called after, callback
        });
        return output;
    };
    var output = parseSheet("https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json");
    console.log(output); // this will called first and log out empty string.
    </script>
</body>
</html>
Joe
  • 279
  • 1
  • 4
  • 15

1 Answers1

0

To change it to callback:

    <script defer="true">
    var parseSheet = function(url, callback) {
        var output = "";
        $.getJSON(url, function(data) {
            output = data.version;
            callback(output); // this will called after, callback
        });
    };
    var output;  
    parseSheet("https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json", function(out){
       output = out;
    });
    </script>
Zee
  • 8,420
  • 5
  • 36
  • 58