Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
Why does my function not waiting for the API response?

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..

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
       }    
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try logging the instance in the same .then chain in login.

login() {
    this.API.login("username", "password").then((r) => {
        this.API.createInstance(r.data.token).then(() => {
            console.log(this.API.instance);
        )};
    });
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda