【问题标题】:Why does my function not waiting for the API response?为什么我的函数不等待 API 响应?
【发布时间】: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


    【解决方案1】:
    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()... 中调用了this.API.createInstance(r.data.token) 吗?
    • 好的,它适用于实例,但现在我的实例已初始化,我尝试了类似 getGames(){ this.instance.get("api.com/games").then((r) => { this._games = r })} 的操作,但它不起作用,我应该在哪里调用 getGames()? (在我的 API 类中)
    • 抱歉耽搁了您的时间。但 r 在我的情况下是未定义的。当我在console.log(r) 之后调用this.API.games 时,我也有一个空对象
    • getGames(){ return this.instance.get("api.com/games"),我的代码将工作
    • 没错!我打算写 getGames() 中缺少返回,但现在它正在工作。非常感谢你!我现在明白了,当时我不知道我可以使用多个。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多