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

sandaur's avatar

Make execution wait for Axios call to finish

I have this function called isSubdomAvailable() that makes an axios call, i want to make the execution of the function to wait for the axios call to finish so the messages show up in the right order.

My code:

    isSubdomAvailable(subdom){
                let trimedSubdom = subdom.trim();
                if (!trimedSubdom || this.lastCheckedSubdom == trimedSubdom) {return false;}
                this.subdomLoading = true;
                this.lastCheckedSubdom = trimedSubdom
                
                axios.get('/api/subdomav/'+trimedSubdom).then(response => {
                    this.subdomLoading = false;
                    this.subdomAvail = response.data.available;
                    console.log(response);
                    console.log("i should go first");
                }).catch(({response}) => {
                    this.subdomLoading = false;
                    this.subdomAvail = false;
                    console.log(response);
                });
                console.log("i should go second");
            }

What i have tried:

async isSubdomAvailable(subdom){
    ...
    ...
    const axiosCall = await axios.get(...
}

/* This didn't work*/
isSubdomAvailable(subdom){
    ...
    ...
    await axios.get(...
}

/* This didn't work either*/

I'll thanks any advise.

0 likes
2 replies
topvillas's avatar

then doesn't stop the function from continuing, it just calls the lambda when a promise is returned from axios.

async/await will wait for axios to make the call but you'll need to put some code after it.

Amersfoj's avatar

Axios has a method called finally() which runs after the call finishes. Just like the then() and catch() methods finally() is called after a response is received. Keep in mind that this runs regardless of the request success, so even after catching the error and show it, the final code will still run. So your code should go in there like so:

 axios.get('/api/subdomav/' + trimedSubdom).then(response => {
                    this.subdomLoading = false;
                    this.subdomAvail = response.data.available;
                    console.log(response);
                    console.log("i should go first");
                }).catch(({response}) => {
                    this.subdomLoading = false;
                    this.subdomAvail = false;
                    console.log(response);
                }).finally(() => {
                    console.log("i should go second");
                });
1 like

Please or to participate in this conversation.