Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

export default {     data () {         return {             id: null,             alias: null,             valid: true,         }     },      methods: {         // triggered by the save button         save () {             this.valid = true;             console.log('before checking');              this.checkUniqueness();             // other validations here              if (this.valid) {                 console.log('3. checked valid, can save now');                 // save now             }         },          checkUniqueness () {             axios.get('/api/unique/alias', {                 params: {                     id: this.id,                     alias: this.alias,                 }             })                 .then((response) => {                     console.log('2. server response:' + response.data.unique)                     this.valid = response.data.unique;                 });         },      }, } 

The console shows the following result:

1. before checking 3. checked valid, can save now 2. server response:false 

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)?

like image 769
Warrio Avatar asked Sep 21 '17 15:09

Warrio


People also ask

Is Axios synchronous or asynchronous?

Axios is a promise-based HTTP request library that allows us to interact with rest API's. Because Axios is a promise-based library it supports making asynchronous request so that your browser can function normally while waiting for the request to be handled.

Is Axios asynchronous?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

How do you handle Axios promises?

Promises can be handled in two ways using modern JS - the async/await syntax, which was shown above, as well as . then() and . catch() methods.

What is an Axios promise?

Axios is a simple promise based HTTP client for the browser and node. js. Axios provides a simple to use library in a small package with a very extensible interface.

How do I make multiple requests in Axios?

Because axios utilizes promises, it uses a familiar promise method. We can have multiple request happen simultaneously with the axios.all () method. This method takes in an array of requests and returns and object if both request resolves. even though it can take multiple request we only need to chain on one then () and one catch () to it.

How do I use the async/await syntax in Axios?

In a new file getRequestAsyncAwait.js, add the following code: To use the async/await syntax, we need to wrap the axios.get () function call within an async function. We encase the method call with a try...catch block so that we can capture any errors, similar to the catch () method we used in the Promise version.

How do I get the data from Axios?

To perform this request when the component mounts, you use the useEffect hook. This involves importing Axios, using the .get () method to make a GET request to your endpoint, and using a .then () callback to get back all of the response data.

How do we interact with Axios?

We interact with Axios using Promises, or the async/await keywords which are an alternative syntax for using Promises. If you are using CommonJS, there are two methods in Node.js to import the library.


Video Answer


2 Answers

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:

checkUniqueness () {     return axios.get('/api/persons/unique/alias', {         params: {             id: this.id,             alias: this.alias,         }     })     .then((response) => {         console.log('2. server response:' + response.data.unique)         this.valid = response.data.unique;     }); } 

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

this.checkUniqueness() .then((returnVal) => {    // other validations here   //  save }) .catch(err => console.log("Axios err: ", err)) 

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

.then((response) => {     console.log('2. server response:' + response.data.unique)     return response.data.unique;  }); 

then in save:

this.checkUniqueness() .then((valid) => {     if (valid) // do something    // other validations here    //  save }) 
like image 110
Mark Avatar answered Sep 24 '22 07:09

Mark


If you just do what JS docs (mozilla) show you can treat Axios as just another promise. Be careful about making the request synchronous bc it can freeze the UI and the rest of your app.

       async save () {             this.valid = true;             console.log('before checking');              const isUnique = await this.checkUniqueness();             console.log(isUnique); // => value waited for and returned from this.checkUniqueness()             // other validations here              if (this.valid) {                 console.log('3. checked valid, can save now');                 // save now             }         } 
like image 22
Taysky Avatar answered Sep 25 '22 07:09

Taysky