I have a class that is using an API, I have all my request inside this class.
export default class API {
constructor() {
this._instance = {};
}
get instance() {
return this._instance;
}
set instance(newInstance) {
this._instance = newInstance;
}
login(username, password) {
return axios.post("thisisanexample.com/login", {
username: username,
password: password,
});
}
createInstance(token) {
this._instance = axios.create({
baseURL: "thisisanexample.com",
timeout: 1000,
headers: { Authorization: "Bearer " + token },
});
}
}
And I use it inside a Vue Component
import Api from "../api.js"
export default{
name : "login",
data : () => ({
API : {
instance: null,
},
}),
mounted() {
this.API = new Api();
}
methods : {
login(){
this.API.login("username", "password").then((r) => {
this.API.createInstance(r.data.token);
});
}
isInstanceWorking(){
console.log(this.API.instance);
}
}
When I call the function isInstanceWorking() the first time (event click on a button), it gives me an empty object and when I press a second time on the button, it gives me an instance. I think it's because the first time, my API didn't receive the response and when I call it a second time, my API receive it (it didn't wait for the response).
So after some researches, I find that it might be because of not using things like await, async, or then. But I tried to use them but it didn't work for me.
So my question is, how can I say to my function to wait a response and then do something ? What I am doing wrong ?
In the future I wanna add others requests to my API like this.games = this.API.games (return the games for the current instance) etc..