I am currently working on a class that utilizes an API, where all the requests are handled within 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 },
});
}
}
Within a Vue Component, I incorporate this class.
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);
}
}
Upon calling the function isInstanceWorking()
for the first time (on a button click event), it returns an empty object. However, when clicked again, it displays an instance. This is likely due to the fact that the initial call did not wait for the response, but the subsequent one did.
After conducting some investigation, I have learned that using keywords like await, async, or then might help resolve this issue. Despite my attempts to utilize them, I have not been successful.
My question now is, how can I ensure that my function waits for a response before proceeding? What could be the error in my approach?
In the future, I plan to integrate additional requests to my API such as this.games = this.API.games
, which will return the games for the current instance.