Member-only story
Introduction:
Scenario: When entering a specific page in a web application, multiple API calls are made simultaneously. In such cases, when a token is required, and Axios is used for making requests, it’s common to handle token retrieval in the request interceptor. Typically, this leads to triggering the token request API multiple times if there are concurrent calls to other APIs. The ideal solution is to ensure that all APIs use the token from the initial request, avoiding redundant token requests.
Solution:
To achieve this, we can create a function that triggers multiple times but only returns the result of the first request.
function repeatOnce(getResult, local_name) {
return new Promise(async (resolve) => {
const local_result = localStorage.getItem(local_name);
if (local_result) {
console.log('%c [Exists] - 1166', 'font-size:13px; background:pink; color:#bf2c9f;');
resolve(local_result);
} else {
if (!repeatOnce.count) {
repeatOnce.count = 0;
repeatOnce.count++;
console.log('%c [Just entered the application page, result not cached, needs to request and cache locally] - 1169', 'font-size:13px; background:pink; color:#bf2c9f;');
const request_result = await getResult();
localStorage.setItem(local_name, request_result);
resolve(request_result)…