0

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!

Bryan
  • 3
  • 1
  • An async function will wrap its return value in a Promise (since you're using ES6 features here, consider using `fetch()` which return a Promise already) – Nick Parsons Feb 15 '21 at 09:05
  • 1
    @PatrickRoberts meh, I was on the edge of adding it but decided not to, as it focuses on "why" rather than "what to do with this". I think the initial dupe was more on point. I guess it doesn't really hurt either way. – VLAZ Feb 15 '21 at 09:11

0 Answers0