Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda