Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bennettblack's avatar

How to properly use Async / Await with Axios post request?

When I trigger this method, I am instantly redirected and no data is posted. If i remove the redirect, my data is posted. After some research, I believe the issue is that I'm being redirected before my post(s) happen and that I need to use Async / Await however I've been unable to generate a working solution.

postGame(){

            let self = this;
            axios.post('/api/darts', self.fields)
                .then(function (response) {

                })
                .catch(function (error) {
                    console.log(error);
                });


            axios.post('/api/totals', self.totals)
                .then(function (response2){

                })
                .catch(function (error){
                    console.log(error);
                });

            //Redirect
            location.href = '/games';

        },
0 likes
1 reply
erikgall's avatar
erikgall
Best Answer
Level 14

@bennettblack The problem is that you are not waiting for your promises to finish before redirecting. Your redirect would have to be inside one of the then callbacks to work. But since you asked about async and await here is how you would do that:


async postGame() {
	try {
		const dartsResponse = await axios.post('/api/darts', this.fields)

		const totalsResponse = await axios.post('/api/totals', this.totals)

		location.href = '/games'
	} catch (e) {
		// handle whatever error happened 
	}
}
1 like

Please or to participate in this conversation.