我正在努力将这个模式包裹在我正在努力实现的模式中,所以我希望堆栈溢出社区可以帮助我解决这个问题 .

目前我使用 redux-thunksuperagent 处理对我的调用API并将其与redux同步

这可能是一个例子

export const getUser = (id) => {
  return (dispatch) => {
    const deferred = new Promise((resolve, reject) => {
      const call = () => {
        API.get(`/users/${id}`)
        .then((response) => response.body)
        .then((response) => {
          if (response.message === 'User found') {
            serializeUser(response.data).then((response) => {
              resolve(response);
            });
          } else {
            reject('not found');
          }
        }).catch((err) => {
          handleCatch(err, dispatch).then(call).catch(reject)
        });
      }
      call()
    });
    return deferred;
  };
};

在服务器返回200和一些数据的情况下,我继续将数据放入存储并呈现到页面或我的应用程序所做的任何事情 .

在我收到错误的情况下,我试图编写一个函数来拦截它们并确定它是否应该在页面上显示错误,或者在我们的API中显示401的情况下,尝试令牌刷新然后尝试调用该方法...

import { refreshToken } from '../actions/authentication';

export default (err, dispatch) => {
  const deferred = new Promise((resolve, reject) => {
    if (err.status === 401) {
      dispatch(refreshToken()).then(resolve).catch(reject)
    } else {
      reject(err);
    }
  })
  return deferred;
};

但是,我必须将此添加到每个调用,并且它不会考虑在正在进行刷新时不应尝试调用的并发调用 .

我在这个主题的研究中看到了一些可能_2975220可能有用的东西但是我无法将我的大脑包围起来如何使这项工作

基本上,我需要像我的所有API请求将进入的队列,这可能是去抖动的,因此任何并发请求都将被推到最后,一旦超时结束,调用就会被堆叠起来,当第一次调用获得401时暂停队列,直到令牌刷新成功返回,在这种情况下它继续队列或失败,在这种情况下它会取消队列中的所有未来请求并将用户发送回登录页面

我在这里担心的是,如果堆栈中的第一个呼叫需要很长时间,我不希望其他呼叫必须等待很长时间,因为它会增加用户感知的加载时间

有没有更好的方法来处理保持令牌刷新?