1. Problem Scenario Analysis
Repeated requests may result when:
- Users frequently click on the trigger button event
- Quickly remount/update components
- Real-time search request for input box (such as anti-shake failure)
- Multiple independent components load the same data at the same time
2. Core implementation ideas
- Create a request cache pool: Store ongoing requests
- Request a unique identifier: Generate request unique keys through parameters
- Promise reuse: The same request returns the cached Promise
- Cache cleaning mechanism: Automatically clean the cache after the request is completed
3. Complete implementation plan
1. Basic version implementation (ES6+)
// Request cache poolconst requestCache = new Map(); function generateRequestKey(config) { return `${}-${}-${()}`; } async function sharedRequest(config) { const requestKey = generateRequestKey(config); //The same request exists in progress if ((requestKey)) { return (requestKey); } // Create a new request and cache it const requestPromise = axios(config) .then(response => { (requestKey); // Clear cache successfully return response; }) .catch(error => { (requestKey); // Clear cache even if it fails throw error; }); (requestKey, requestPromise); return requestPromise; }
2. Advanced Feature Enhanced Edition
class RequestPool { constructor() { = new Map(); = 5000; //Default cache for 5 seconds } getKey(config) { const { method, url, params, data } = config; return `${method}-${url}-${(params)}-${(data)}`; } async request(config) { const key = (config); const now = (); // There is an unexpired cache if ((key)) { const { expire, promise } = (key); if (expire > now) return promise; } // Create a new request const promise = axios(config).finally(() => { // Automatically clean or retain cache if (!) { (key); } }); // cache with validity period (key, { promise, expire: () + ( || ) }); return promise; } // Manually clear cache clearCache(key) { (key); } } // Use exampleconst apiPool = new RequestPool(); function fetchUserData(userId) { return ({ method: 'GET', url: '/api/user', params: { id: userId }, cacheTTL: 10000 // Custom cache time }); }
4. Key points analysis
1. Request a unique logo design
Combining key parameters: method + url + serialized params/data
Serialization optimization:
function stableStringify(obj) { const keys = (obj).sort(); return ((k => ({ [k]: obj[k] }))); }
2. Cache Cleanup Policy
Policy Type | Implementation method | Applicable scenarios |
---|---|---|
Instant cleaning | Delete immediately after the request is completed | General data requests |
TTL Expired | Check Expire field | Data that requires short-term cache |
Manual cleaning | Provide clearCache method | Clearly know when data changes |
LRU algorithm | Maintenance usage records + maximum quantity limit | High frequency request and memory sensitive scenarios |
3. Key points for error handling
.catch(error => { // Special error handling: Network errors can retain temporary cache if () { setTimeout(() => (key), 1000); } throw error; });
5. Comparison of applicable scenarios
plan | advantage | shortcoming | Best use scenarios |
---|---|---|---|
Basic version | Simple implementation and low memory usage | Lack of advanced control | Simple pages, small amount of APIs |
Package version | Perfect functions and strong expansion | Highly complex implementation | Medium- and large-scale projects and complex scenarios |
Third-party library (swr) | Out of the box, rich in features | Need to learn new API | Complex caching requirements that need to be implemented quickly |
6. Extended optimization direction
- Request for racing processing:
let abortController; function smartRequest() { if (abortController) { (); } abortController = new AbortController(); return fetch(url, { signal: }); }
- Local cache fusion:
const response = await request(); if () { (cacheKey, { data: , expire: () + 3600000 }); }
- Visual monitoring:
// Add in RequestPool classgetCacheStatus() { return (()).map(([key, item]) => ({ key, expireIn: - (), status: ? 'pending' : 'settled' })); }
Through this implementation method, the following problems can be effectively solved:
- Reduce duplicate network requests by 50%-90%
- Avoid performance loss caused by repeated rendering of components
- Ensure data consistency between multiple components
- Reduce concurrent pressure on the server
In actual projects, you can choose the basic version or enhanced version to implement it according to specific needs. It is recommended to cooperate with TypeScript to perform type constraints to ensure the robustness of the code.
The above is the detailed content of the code example for solving the front-end duplicate requests through shared Promise. For more information about sharing Promise to solve the duplicate requests, please follow my other related articles!