title: Accessing indexedDB in ServiceWorker. Race condition
body: <p>There aren't many examples demonstrating indexedDB in a ServiceWorker yet, but the ones I saw were all structured like this:</p>
  
  <pre><code>const request = indexedDB.open( 'myDB', 1 );
  var db;
  
  request.onupgradeneeded = ...
  
  request.onsuccess = function() {
      db = this.result; // Average 8ms
  };
  
  
  self.onfetch = function(e)
  {
      const requestURL = new URL( e.request.url ),
      path = requestURL.pathname;
  
      if( path === '/test' )
      {
          const response = new Promise( function( resolve )
          {
              console.log( performance.now(), typeof db ); // Average 15ms
  
              db.transaction( 'cache' ).objectStore( 'cache' ).get( 'test' ).onsuccess = function()
              {
                  resolve( new Response( this.result, { headers: { 'content-type':'text/plain' } } ) );
              }
          });
  
          e.respondWith( response );
      }
  }
  </code></pre>
  
  <p>Is this likely to fail when the ServiceWorker starts up, and if so what is a robust way of accessing indexedDB in a ServiceWorker?</p>