如何在3次请求后中断此Javascript HTTP无限请求循环?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在3次请求后中断此Javascript HTTP无限请求循环?相关的知识,希望对你有一定的参考价值。

所以我有2个组件,Token.jsx和httpRequest.jsx。当令牌到期时它们都互相调用并进入无限循环,我想在3个http错误之后打破循环。

export default function GenerateToken() {
  return new Promise(((resolve) => {
    const refreshToken = GetRefreshToken();
    const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
    const headers = {
      'Content-Type': 'application/json',
    };
    const params = {
      refreshToken,
    };
    httpRequest.makeHTTPCall('post', url, headers, params).then((tokenObject) => {
      // Storing the idToken in localstorage
      // reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
      StoreIdToken(`Id ${tokenObject.id_token}`);
      StoreUserId(tokenObject.user_id);
      StoreRefreshToken(tokenObject.refresh_token);
      resolve(tokenObject.id_token);
    });
  }));
}

//第二个文件

function makeHTTPCall(method, url, headers, params = null) {
  return new Promise((resolve, reject) => {
    headers.Authorization = GetIdToken();
    headers['Content-Type'] = 'application/json';
    qwest.setDefaultDataType('json');
    qwest.setDefaultOptions({
      headers,
    });

    // Make http request
    qwest[`${method}`](url, params)
      .then((xhr, response) => {
        resolve(response);
      })
      .catch((error, xhr) => {
        if (xhr.status === 401) { // IdToken expired
          GenerateToken().then(() => {
            resolve(GET(url));
          });
        }
        else {
          reject(error); // error
        }
      });
  });
}
答案

你可以给它们两个像tryCount这样的参数,并在其中一个函数中递增它,一旦它达到2就拒绝它:

export default function GenerateToken(tryCount = 0) {
  return new Promise((resolve) => {
    const refreshToken = GetRefreshToken();
    const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
    const headers = {
      'Content-Type': 'application/json',
    };
    const params = {
      refreshToken,
    };
    httpRequest.makeHTTPCall('post', url, headers, params, tryCount).then((tokenObject) => {
      // Storing the idToken in localstorage
      // reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
      StoreIdToken(`Id ${tokenObject.id_token}`);
      StoreUserId(tokenObject.user_id);
      StoreRefreshToken(tokenObject.refresh_token);
      resolve(tokenObject.id_token);
    });
  });
}
// 2nd File

function makeHTTPCall(method, url, headers, params, tryCount) {
  return new Promise((resolve, reject) => {
    headers.Authorization = GetIdToken();
    headers['Content-Type'] = 'application/json';
    qwest.setDefaultDataType('json');
    qwest.setDefaultOptions({
      headers,
    });

    // Make http request
    qwest[`${method}`](url, params)
      .then((xhr, response) => {
        resolve(response);
      })
      .catch((error, xhr) => {
        if (xhr.status === 401 && tryCount <= 1) { // IdToken expired, and we've recursed less than twice so far
          GenerateToken(tryCount + 1).then(() => {
            resolve(GET(url));
          });
        } else {
          reject(error); // error
        }
      });
  });
}

另请注意,您应该避免使用explicit Promise construction antipattern

export default function GenerateToken(tryCount = 0) {
  const refreshToken = GetRefreshToken();
  const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
  const headers = {
    'Content-Type': 'application/json',
  };
  const params = {
    refreshToken,
  };
  return httpRequest.makeHTTPCall('post', url, headers, params, tryCount).then((tokenObject) => {
    // Storing the idToken in localstorage
    // reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
    StoreIdToken(`Id ${tokenObject.id_token}`);
    StoreUserId(tokenObject.user_id);
    StoreRefreshToken(tokenObject.refresh_token);
    return tokenObject.id_token;
  });
}
// 2nd File

function makeHTTPCall(method, url, headers, params, tryCount) {
  headers.Authorization = GetIdToken();
  headers['Content-Type'] = 'application/json';
  qwest.setDefaultDataType('json');
  qwest.setDefaultOptions({
    headers,
  });

  // Make http request
  return qwest[`${method}`](url, params)
    .then((xhr, response) => {
      return response;
    })
    .catch((error, xhr) => {
    if (xhr.status === 401 && tryCount <= 1) { // IdToken expired, and we've recursed less than twice so far
      return GenerateToken(tryCount + 1).then(() => {
        return GET(url);
      });
    } else {
      throw new Error(error);
    }
  });
}

以上是关于如何在3次请求后中断此Javascript HTTP无限请求循环?的主要内容,如果未能解决你的问题,请参考以下文章

Chrome 调试 - 下一次点击事件中断

请教一个关于51单片机外部中断的问题

一次排查页面重复请求的经历

tcp三次握手 以及四次挥手

如何从 fetch javascript 请求的响应中获取数据

如何在javascript中克隆图像