Blog>
Snippets

Implementing Race Strategy (Fastest Response)

A code snippet implementing a 'race' strategy where both the cache and the network are queried in parallel and the fastest response is used.
function fetchData(url) {
  // Create two promises: one for cache and one for network
  const fromCache = caches.match(url);
  const fromNetwork = fetch(url);

  // Start both requests in parallel and use the first fulfilled promise
  return Promise.race([fromCache, fromNetwork])
    .then(response => {
      // Check if we got a valid response
      if(response && response.ok) {
        return response.json(); // Parse JSON if response is ok
      }
      throw new Error('No valid response obtained.');
    });
}
This function 'fetchData' initiates two parallel requests to retrieve data from cache and the network. It then races the two promises and returns the data from the fastest one. If both fail or return an invalid response, it throws an error.