Blog>
Snippets

Caching Asynchronous Validation Results

Provide an example of caching validation results from asynchronous operations to optimize performance and reduce unnecessary server requests for known valid or invalid inputs.
const validationCache = new Map();
Initialize a cache using JavaScript Map to store validation results.
async function validateUsername(username) {
  // Check if the result is in the cache first
  if (validationCache.has(username)) {
    return validationCache.get(username);
  }
  // Simulate an asynchronous validation, e.g., API call
  const isValid = await fetch(`/api/validate-username?username=${username}`)
    .then(response => response.json())
    .then(data => data.isValid);
  // Cache the validation result
  validationCache.set(username, isValid);
  return isValid;
}
Defines an asynchronous function to validate a username. It first checks the cache for the result. If not found, it performs the validation (simulated here by an API call) and caches the result before returning it.
// Usage example
validateUsername('john_doe').then(isValid => {
  console.log('Is valid:', isValid);
});
Demonstrates how to use the validateUsername function, which utilizes the cached results for optimization.