I try to get content with an async call and grab the response via an async function. What is wrong with this setup? The result of the console log is always undefined?
_json: function (callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', this.options.url, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
},
get: async function () {
var resp = await this._json(function(response) {
return JSON.parse(response);
});
console.log(resp);
}
CodePudding user response:
Your _json
function is not a Promise. It uses common callback pattern to pass information back asynchronously. You have to wrap it in a Promise first, if you want to use async/await syntax.
new Promise((resolve) => this._json((response) => resolve(JSON.parse(response)))
Then you can await
it and receive parsed JSON (as you expect).
CodePudding user response:
In order to use async / await
you need to know when to use await
in the first place. You cannot just put simply await
infront of anything and expect that it somehow awaits something.
So, when should you use await
or lets say when does it make sense to use it?
One simple question:
- Does your method / function returns an Promise?
- Yes: You can put
await
infront of it - No: Its useless to use
await
- Yes: You can put
We can make that check on your issue:
Does this._json()
returns an Promise?
In your case no
. That means using await
is useless.
What you can do is returning an promise:
_json: function () {
return new Promise((res, rej) => {
var xobj = new XMLHttpRequest()
xobj.overrideMimeType('application/json')
xobj.open('GET', this.options.url, true)
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status === 200) {
res(xobj.responseText)
} else {
rej('Something went wrong')
}
}
xobj.send(null)
})
},
get: async function () {
var resp = await this._json()
console.log(resp)
},
this._json()
returns an Promise now. In this case it makes sense to use await
.
Remember: By putting async
infront of an function,your function then returns also an promise.