0

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.

wurstm162
  • 71
  • 1
  • 6
  • *"How to ... return"*: by using a `return`. Your getter does not return anything. – trincot Apr 26 '21 at 07:57
  • `fetch_user` doesn't `return` anything. You need to `return fetch(...)`. That'll return a promise. Which means the getter can at best return a promise, not the user directly. There's no way around that. – deceze Apr 26 '21 at 07:58
  • 1
    ...and drop the final `.then`: it serves no purpose. Also be aware that `abc.user` will return a promise once you have that `return`. There is no way you can retrieve *now* which is only available in a *future*. You'll always need to await a promise. – trincot Apr 26 '21 at 07:59

0 Answers0