为什么我的函数不等待API响应?



我有一个使用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(返回当前实例的游戏)等。

createInstance(token) {
this._instance = axios.create({
baseURL: "thisisanexample.com",
timeout: 1000,
headers: { Authorization: "Bearer " + token },
})
}
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) => {
return this.API.createInstance(r.data.token);
})
.then(()=>{
//call isInstanceWorking
return this.API.getGames()
})
.then(r=>{
console.log(r);// games data
})
}
isInstanceWorking(){
console.log(this.API.instance);
}    
}

尝试在login中记录同一.then链中的实例。

login() {
this.API.login("username", "password").then((r) => {
this.API.createInstance(r.data.token).then(() => {
console.log(this.API.instance);
)};
});
}

最新更新