Why is my variable not being passed outside function [duplicate]

Im trying to store some local json data in a new nested object and i can access the json using XMLHttpRequest but I cant find a way to make the local variable accessable outside the function. Ive tried lots of ways (setting the variable at the start of the file, using let, const and var, trying return statement in the function but I cant get it to work. Ive simplified the code im using. Sorry its a bit basic but im stuck.

John

var XMLHttpRequest = require('xhr2'); 
var xhr = new XMLHttpRequest();

//Load Shelly JSON
var req = new XMLHttpRequest();
var url = "http://192.168.0.242/rpc/Shelly.GetStatus";
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = 
        function () {
            var shellyResponse = req.response;
            dayusage = shellyResponse["switch:0"].aenergy.total;
        
};
req.send(null);

console.log(dayusage);