【问题标题】:Axios - multiple requests for the same resourceAxios - 对同一资源的多个请求
【发布时间】:2018-02-17 18:53:58
【问题描述】:

我正在创建一个应用程序,其中在一个页面中,我有两个组件请求相同的 http 资源。在这种情况下,我使用的是 axios,这是一个示例:

axios.get('/api/shift/type')
        .then(
            (response) => {
                self.shiftTypes = response.data;
                success(response.data)
            },
            (response) => {
                error(response)
            }
        );

问题在于他们几乎同时提出请求。如果组件 A 与组件 B 同时发出请求,则进行 2 次请求调用,它们将获得相同的数据。有没有办法检查 axios 当前是否有未解决的承诺,并在请求解决后将结果返回给两个组件?

不确定是否有帮助,但该应用正在使用 vue 框架构建

谢谢

编辑:我尝试将承诺存储在内存中,但组件 B 从未得到响应

getShiftTypes(success, error = this.handleError, force = false) {
    if (this.shiftTypes && !force) {
        return Promise.resolve(this.shiftTypes);
    }

    if (this.getShiftTypesPromise instanceof Promise && !force) { return this.getShiftTypesPromise; }

    let self = this;
    this.getShiftTypesPromise = axios.get('/api/shift/type')
        .then(
            (response) => {
                self.shiftTypes = response.data;
                self.getShiftTypesPromise = null;
                success(response.data)
            },
            (response) => {
                error(response)
            }
        );
    return this.getShiftTypesPromise;
}

【问题讨论】:

  • 我猜你需要为这种情况创建一些 util 脚本来检查 axios 承诺的当前状态到特定的 url 并返回它而不是创建新的。
  • @Vadim 我已经用完整的函数更新了这个问题——我目前有一个“服务”类,它具有 getShiftTypes() 作为函数,每个组件都调用该函数——我目前正在存储承诺在内存中,但在 promise 解决后组件 B 没有得到任何数据

标签: javascript promise vuejs2 axios


【解决方案1】:

考虑使用缓存:

let types = { lastFetchedMs: 0, data: [] }

async function getTypes() {

  const now = Date.now();

  // If the cache is more than 10 seconds old
  if(types.lastFetchedMs <= now - 10000) {
    types.lastFetchedMs = now;
    types.data = await axios.get('/api/shift/type');
  }

  return types.data;
}

while(types.data.length === 0) {
  await getTypes();
}

【讨论】:

  • 我尝试了类似的方法,我将在问题中发布,但组件 B 的成功承诺没有生效。如果是用户错误,请告诉我。
  • 嗯,实际上我不知道你是否可以多次使用.then()。也许更好的解决方案是缓存响应。有一个看起来像这样的对象“类型”:let types = { timestamp: 1234567, types: []}
  • 我用我认为可行的方法编辑了我的答案 :-)。
  • 看起来不太干净,但我会试一试
  • 还没有机会测试它。可能会在下周末左右试一试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 2021-11-23
相关资源
最近更新 更多