Вы можете дать им обоим параметр, например 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
}
});
});
}
Также обратите внимание, что вам следует избегать явное обещание строительства антипаттерна :
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);
}
});
}