Async request promise help

Hey,

I was writing a short function, to get data from a PHP File, the function looks like this:

async function getData(uri) {
    let promise = new Promise((resolve, reject) => {
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
            if(this.readyState == 4 && this.status == 200){
                resolve(this.ResponseText);
            }
        }
        xhttp.open("GET", "https://coolwebsite.com/game/actions/" + uri)
        xhttp.send();
    })
    let result = await promise;
    return result;
}

However, when I try to get the data and output it in the console log, it returns a pending promise.

Promise { <state>: "pending" }

Can you help me find my error in the code, to output the real value?
Thanks!

try this

getData('').then(function(e){console.log(e)}).catch(function(e){console.log(e)})

you must subscribe to you async callback

Hi there,

This happens when you try to console.log the output of getData function?

If so, then this is expected because what async does it makes your function return a promise. So you can do for example:

getData('uri...').then(data => {
  console.log(data);  
});

Thanks for the reply.
When I try your solution it now outputs me “undefined”, but the file I’m trying to get the data from returns JSON stuff.

check that

this.responseText

I checked it, when I try

console.log(this.responseText)

inside the function
it outputs the value I want, but I’d like to get it as a return, not to print it directly into the console.

 function getData(uri) {
    return new Promise((resolve, reject) => {
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
            if(this.readyState == 4 && this.status == 200){
                resolve(this.responseText);//here parse it to json if you like
            }
        }
        xhttp.open("GET", "https://coolwebsite.com/game/actions/" + uri)
        xhttp.send();
    })
    
}

Maybe to simplify it just use fetch

Thank you very much, fetch made everything working