How to make axios synchronous

后端 未结 3 1140
情深已故
情深已故 2020-12-14 07:00

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 resp

3条回答
  •  难免孤独
    2020-12-14 07:07

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

提交回复
热议问题