0

I am new to Javascript and ran into a problem I can't resolve. I wanted to rewrite an example with jquery into pure Javascript.

I don't understand why this doesn't work. Why is the variable "vorlauf" empty outside the function? Isn't it a global variable? I attached a picture of the console output.

Not working as expected (tried to omit every clutter...):

 <!DOCTYPE HTML>
    <html>
        <head>
            <script>
                let vorlauf = new Array();

                let getJSON = function (name) {
                    fetch(name + ".json")
                        .then(response => response.json())
                        .then(parsed =>   {
                            console.log(parsed.length, parsed)
                            for (let i = 0; i < parsed.length; i++) {
                                vorlauf.push({
                                    x: new Date(parsed[i].date + " " + parsed[i].time),
                                    y: Number(parsed[i].temp) / 1000
                            })
                        }
                    });
                }
                getJSON("vorlauf")
                console.log("Nach Aufruf getJSON " + vorlauf.length)

            </script>
        </head>
        <body>
        </body>
    </html>

Works as expected (included everything):

!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {

let vorlauf = [];

let chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        theme: "light2",
        title: {
                text: "Vorlauf"
        },
        axisY: {
                title: "Grad",
                titleFontSize: 24
        },
        axisX:{      
            valueFormatString: "YYYY-MM-DD hh:mm:ss" ,
            labelAngle: -50
        },
        data: [{
                name: "Vorlauf",
                showInLegend: true,
                type: "spline",
                dataPoints: vorlauf
        }]
});

$.getJSON("http://localhost/vorlauf.json", function(data) {         
            for(let i = 0; i < data.length; i++) {
                vorlauf.push({
                        x: new Date(data[i].date + " " + data[i].time),
                        y: Number(data[i].temp) / 1000
                });
          }
    chart.render();
      })
}

</script>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>

The json data:

[{"date": "2020-02-22", "temp": "39937", "time": "09:28:59"}, {"date": "2020-02-22", "temp": "39937", "time": "09:29:21"}]

picture of the debug output of Firefox

Barruda
  • 11
  • `fetch` is asynchronous, so although `console.log("Nach Aufruf getJSON " + vorlauf.length)` occurs after the fetch _in the text of the program_, it is run _before_ the result of the `fetch` is returned. – Ben Aston Feb 22 '20 at 23:18
  • Thank you for this information. – Barruda Feb 22 '20 at 23:22
  • This did it for me! Thx @Ben&Jonas async function getJSON(a) { try { var r = await (await fetch(a)).json(); for (let i = 0; i < r.length; i++) { vorlauf.push({ x: new Date(r[i].date + " " + r[i].time), y: Number(r[i].temp) / 1000 }) } } catch (e) { console.log(e); } } (async function () { await getJSON("vorlauf.json"); chart.render(); })() – Barruda Feb 23 '20 at 14:27

1 Answers1

-1

Please place all javascript above .

<!DOCTYPE HTML>
<html>

<head>

</head>

<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
    window.onload = function() {

        let vorlauf = [];

        let chart = new CanvasJS.Chart("chartContainer", {
            animationEnabled: true,
            theme: "light2",
            title: {
                text: "Vorlauf"
            },
            axisY: {
                title: "Grad",
                titleFontSize: 24
            },
            axisX: {
                valueFormatString: "YYYY-MM-DD hh:mm:ss",
                labelAngle: -50
            },
            data: [{
                name: "Vorlauf",
                showInLegend: true,
                type: "spline",
                dataPoints: vorlauf
            }]
        });

        $.getJSON("http://localhost/vorlauf.json", function(data) {
            for (let i = 0; i < data.length; i++) {
                vorlauf.push({
                    x: new Date(data[i].date + " " + data[i].time),
                    y: Number(data[i].temp) / 1000
                });
            }
            chart.render();
        })
    }
</script>