Axios - 对同一资源的多个请求

Hug*_*ugo 5 javascript promise axios vuejs2

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

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

问题在于他们几乎同时要求它。如果组件 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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ing 3

考虑使用缓存:

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();
}
Run Code Online (Sandbox Code Playgroud)