javascript – Why this function doesn’t wait to give its answer?


To extract some numbers from a website, I use this JS code (in a HTML page)

let getJSON = (url, callback) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
        let status = xhr.status;
        if (status == 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send();
};

function new_number() {
getJSON('https://qrng.anu.edu.au/API/jsonI.php?length=5&type=uint8&size=6', (err, data) => {
    if (err != null) {
        console.error(err);
    } else {
        let dat = `${data.data}`
    var dat2 = JSON.stringify(dat);
    console.log(dat2);
        return dat2;
    }
});
}

But when I call new_number(); I immediately get “undefined” but one second after the call of “console.log(dat2);” gives the right string. As if the function wants to give something right away without waiting… what should I change please ?