首页 > 解决方案 > 在给定方法内的所有承诺解决后执行方法

问题描述

在 Vue.js 组件中,我有一些使用axios调用 API 的方法。

在不同的情况下,我需要在此方法中的调用解决后执行一些代码,但我不想在链接中添加一堆if语句.then()到 axios 调用中。

methods: {
  callApi() {
    axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something
  },
  secondMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something else
  }
}

如您所见,一旦请求完成firstMethodsecondMethod两者都依赖callApi但应该做不同的事情。我更喜欢将这个逻辑拆分到不同的函数中,而不是在callApi方法中使用条件。有没有办法做到这一点而不必在里面添加这个逻辑 callApi

标签: javascriptvue.jsaxios

解决方案


callApi返回承诺链,然后在firstMethodand中使用并返回它secondMethod

methods: {
  callApi() {
    return axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something
    })
  },
  secondMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something else
    })
  }
}

无论调用callApi,firstMethod还是secondMethod应该检查失败并处理/报告它。


您的原始代码违反了承诺规则之一:该函数应始终返回链或处理拒绝。(是的,那是[99.9% 的时间],不是。)


推荐阅读