axios拦截器上的多个请求

Ron*_*ani 5 javascript concurrency asynchronous race-condition axios

我在我的 React 应用程序中使用库axios
我的拦截器有问题。

我的问题是,假设我同时发生三个请求,并且没有令牌,拦截器会调用三次getUserRandomToken,我希望拦截器会等到我从第一个请求中获取令牌,然后继续处理其他请求。

PS 他的令牌有过期日期,所以我也检查它,如果过期日期无效,我需要创建一个新令牌。

这是拦截器:

axios.interceptors.request.use(
  config => {
    /*I'm getting the token from the local storage
    If there is any add it to the header for each request*/
    if (tokenExist()) {
      config.headers.common["token"] = "...";
      return config;
    }
    /*If there is no token i need to generate it
     every time create a random token, this is a axios get request*/
    getUserRandomToken()
      .then(res => {
        /*add the token to the header*/
        config.headers.common["token"] = res;
        return config;
      })
      .catch(err => {
        console.log(err);
      });
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);
Run Code Online (Sandbox Code Playgroud)

Ori*_*ice 1

处理令牌生成的单例对象怎么样?与此类似的东西:

const tokenGenerator ={
  getTokenPromise: null,
  token: null,
  getToken(){
    if (!this.getTokenPromise){
      this.getTokenPromise = new Promise(resolve=>{
        /*supposed to be a http request*/
        if (!this.token){
          setTimeout(()=>{
            this.token = 'generated';
            resolve(this.token);
          },0)
        }else{
          resolve(this.token);
        }
      })
    }
    return this.getTokenPromise;
  }
Run Code Online (Sandbox Code Playgroud)

您可以从拦截器引用同一个对象。

参见示例:JS FIDdle 参考:参考