Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Hi you must send your promise in a variable like this and if you use await you can’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)
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading