Skip to content
Advertisement

How to make axios synchronous

I’m using axios to check if an alias has not already been used by another in the database.

Problem: The ajax call doesn’t wait for the server response to execute the remaining code.

The code looks like :

JavaScript

The console shows the following result:

JavaScript

I cannot move the code of the save() method into .then because I do other validations on the input data such as alpha-numeric characters, minimum of characters…

I was able to delay the 3rd part (if (this.valid) {) using set setTimeout but it’s not the best solution. what if the server takes more or less than the defined waiting time..

Question Is there a way to make this call sequential (1, 2, 3) instead of (1, 3, 2)?

Advertisement

Answer

You can’t (or at least really shouldn’t) make it synchronous, so you’ll need a different way forward.

One idea: return the promise from Axios:

JavaScript

and then call then() on it in save():

JavaScript

You could even do all your checking on one place if you returned the value from Axios’s then() rather than setting the flag:

JavaScript

then in save:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement