首页 > 解决方案 > 多个带有返回值的嵌套 axios 调用

问题描述

我正在使用 Vue 并进行多次调用,axios我只是好奇是否有不同的方法。我的代码正在运行,但我不喜欢它的结构方式,我很想就此获得一些意见。

我觉得这太混乱了,可能应该有更好的方法来做到这一点:

login: function() {
    this.toggleLoading();

    this.findUser().then(success => {
        if(success) {
            this.validateSomething().then(success => {
                if(success) {
                    this.auth();
                }
            });
        }
    });
}

findUser并且validateSomething结构如下:

findUser: function() {
    return axios
    .post('/find-user', {
        id: this.id
    })
    .then(response => {
        if(response.data.success) {
            return true;
        } else {
            this.addErrors(response.data.message);
            this.toggleLoading();
            return false;
        }
    })
    .catch(this.catchAll)
},

我不想合并findUserandvalidateSomething函数,因为我希望能够单独使用它们。

但基本上,我试图实现这样的目标:

login: function() {

    this.toggleLoading();

    if(!this.findUser()) {
        return false;
    }

    if(this.validateSomething()) {
        this.auth();
    }
}

这种情况下的最佳实践是什么?

标签: javascriptvue.jsaxios

解决方案


你可以使用 async/await,但如果你对 Promise 没问题,你可以清理它

而不是像这样嵌套承诺:

login: function() {
    this.toggleLoading();

    this.findUser().then(success => {
        if(success) {
            this.validateSomething().then(success => {
                if(success) {
                    this.auth();
                }
            });
        }
    });
}

你可以像这样链接它们:

login: function() {
  this.toggleLoading();

  this.findUser()
    .then(success => {
      if (success) {
        // returning a promise will allow you to chain the next then below
        return this.validateSomething();
      }
      // if success is not truthy, throw error, which will be caught by catch at end and skip other promise execution
      throw new Error('unsuccessful login')
    })
    .then(success => {
      if (success) {
        return this.auth();
      }
      throw new Error('some other reason that it failed')
    })
    .then(success=>{
      return success
    })
    .catch(err=> handle(err)) // then handle the error

}

TL;博士;

Promise(没有 async/await)很好,问题是您像回调一样实现它们,而不是使用.then可以轻松解决的预期方式。


推荐阅读