Ente
February 15, 2021, 8:50am
1
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!
fezeu
February 15, 2021, 9:05am
2
Ente:
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;
}
try this
getData('').then(function(e){console.log(e)}).catch(function(e){console.log(e)})
you must subscribe to you async callback
sitek94
February 15, 2021, 9:06am
3
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);
});
Ente
February 15, 2021, 9:14am
4
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.
Ente
February 15, 2021, 9:26am
6
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.
fezeu
February 15, 2021, 9:31am
7
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();
})
}
sitek94
February 15, 2021, 9:33am
8
Maybe to simplify it just use fetch
Ente
February 15, 2021, 9:37am
9
Thank you very much, fetch made everything working
system
Closed
August 16, 2021, 9:38pm
10
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.