如何使axios同步

How to make axios synchronous

我正在使用 axios 检查别名是否已被数据库中的其他人使用。

问题: ajax 调用不等待服务器响应来执行剩余的代码。

代码如下:

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

    },
}

控制台显示如下结果:

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

我无法将 save() 方法的代码移动到 .then 中,因为我对输入数据进行了其他验证,例如字母数字字符、最少字符...

我可以使用 set setTimeout 延迟第 3 部分 (if (this.valid) {),但这不是最佳解决方案。如果服务器花费的时间多于或少于定义的等待时间怎么办..

问题有没有办法让这个调用顺序为 (1, 2, 3) 而不是 (1, 3, 2)?

你不能(或者至少真的不应该)让它同步,所以你需要一个不同的前进方向。

一个想法:return 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;
    });
}

然后在 save() 中调用 then():

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

如果您 return 从 Axios 的 then() 中编辑值而不是设置标志,您甚至可以在一个地方进行所有检查:

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

然后保存:

this.checkUniqueness()
.then((valid) => {
    if (valid) // do something
   // other validations here
   //  save
})

如果您只是按照 JS 文档 (mozilla) 显示的那样操作,您可以将 Axios 视为另一个承诺。 小心同步请求,因为它会冻结 UI 和您应用的其余部分。

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

axios.get(...) returns a promise(承诺稍后执行的任务) 你可以等待解释器直到这个 promise 以 await ES6+ 中的单词:

let response = await axios.get(...)

axios.get(...) return 是响应,而 axios.get(...).then(...) return 是您想要 return 的响应。所以如果你在 then part 中没有 return 任何东西,它将是 undefined:

let response = await axios.get(...).then() // nothing returns in then
console.log(response) // undefined