【发布时间】:2021-08-25 18:59:50
【问题描述】:
我有一个使用 API 的类,我的所有请求都在这个类中。
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 },
});
}
}
我在 Vue 组件中使用它
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);
}
}
当我第一次调用函数isInstanceWorking()(事件单击按钮)时,它给了我一个空对象,当我第二次按下按钮时,它给了我一个实例。我认为这是因为第一次,我的 API 没有收到响应,而当我第二次调用它时,我的 API 收到了它(它没有等待响应)。
所以经过一些研究,我发现这可能是因为没有使用 await、async 或 then 之类的东西。但是我尝试使用它们,但它对我不起作用。
所以我的问题是,我怎样才能对我的函数说等待响应然后做某事?我做错了什么?
将来我想向我的 API 添加其他请求,例如 this.games = this.API.games(返回当前实例的游戏)等。
【问题讨论】:
标签: javascript vue.js