I want my class to return a user that I fetch from an URL.
export default class CurrentUser{
get user(){
return this.fetch_user();
}
fetch_user(){
fetch("http://127.0.0.1:8000/api/users/current", {
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${localStorage.getItem('token')}`
}
})
.then(res => res.json())
.then((user) => {
return user;
})
}
}
In an another function I tried to call this class like this:
const abc = new CurrentUser();
console.log(abc.user)
Until now all that was returned was an empty object. I think that when I'm calling my function fetch_user() from my getter, the function is returned before the fetch request and the promises are complete.
I tried to implement these solutions below, but I was unsuccessful at doing so.
How to block for a javascript promise and return the resolved result?
How to return promise with a return value
How would one do async JavaScript getters and setters?
Please help me.