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

241
Vistas
Axios: wait till promise is fulfilled

Using axios in React where I am calling an endpoint to fetch JWT token as follows

fetchJwtToken = async () => {
        await axios.post(
            'http://localhost:8080/authenticate',
            {
                username: 'username',
                password: 'password'
            }
        ).then(
            (res) => {
                console.log("JWT token fetch")
                console.log(res)
                this.setState({jwtToken: res.data.jwt})
            }
        )
    }

and then calling this function as follows

processImage = () => {
        this.fetchJwtToken();
        console.log(this.state.jwtToken)
        //use the token to make further calls
}

The function returns a pending promise due to which I think the await completes its execution. This results in empty JWT token to be set in the state.

I want to wait till the token is returned so that I can use it for further calls

How to make it wait till axios returns a fulfilled promise?

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

neither answer address the whole issue

You don't need fetchJwtToken to be async, you can simply return the promise

fetchJwtToken = () => {
        return axios.post(
            'http://localhost:8080/authenticate',
            {
                username: 'username',
                password: 'password'
            }
        ).then(
            (res) => {
                console.log("JWT token fetch")
                console.log(res)
                this.setState({jwtToken: res.data.jwt})
            }
        )
    }

or, if it is async

fetchJwtToken = async () => {
    const res = await axios.post(
        'http://localhost:8080/authenticate',
        {
            username: 'username',
            password: 'password'
        }
    );
    console.log("JWT token fetch")
    console.log(res)
    this.setState({jwtToken: res.data.jwt})
}

either way, where you call it, if you need to wait as well

either

processImage = () => {
    this.fetchJwtToken().then(() => {
        console.log(this.state.jwtToken)
        //use the token to make further calls
    }
}

or

processImage = async () => {
    await this.fetchJwtToken();
    console.log(this.state.jwtToken)
    //use the token to make further calls
}

Your choice, but that will now work as you require

Note: you can use either of the first two fetchJwtToken with either of the two processImage - which ever you want

about 4 years ago · Santiago Gelvez Denunciar

0

Since you're using await / async, I suggest you change your code to this:

const response = await axios.post('http://localhost:8080/authenticate',
        {
            username: 'username',
            password: 'password'
        });

console.log(response.data);
this.setState({jwtToken: response.data.jwt})

If you're more familiar with .then, the above await is equivalent to doing this:

axios.post(...).then((response)=>{})
  
about 4 years ago · Santiago Gelvez Denunciar

0

Hi you must send your promise in a variable like this and if you use await better you don't use .then you must doing like this :

fetchJwtToken = async () => {
        let anyThing = await axios.post(
            'http://localhost:8080/authenticate',
            {
                username: 'username',
                password: 'password'
            }
        )
        console.log(anyThing)
    }
about 4 years ago · Santiago Gelvez 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