This helper function Promise-ifies the operation of opening an IndexedDB database and clearing out the cache when the version changes.
425486
function openDatabase() {
    return new Promise((resolve, reject) => {
      var request = indexedDB.open(dbName, dbVersion);
      request.onerror = reject.bind(null, 'Error opening wasm cache database');
      request.onsuccess = () => { resolve(request.result) };
      request.onupgradeneeded = event => {
        var db = request.result;
        if (db.objectStoreNames.contains(storeName)) {
            console.log(`Clearing out version ${event.oldVersion} wasm cache`);
            db.deleteObjectStore(storeName);
        }
        console.log(`Creating version ${event.newVersion} wasm cache`);
        db.createObjectStore(storeName)
      };
    });
  }
1167527
function(db, opt_err) {

    if (df.hasFired()) {
      goog.log.warning(me.logger, 'database already set.');
    } else if (goog.isDef(opt_err)) {
      goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.');
      me.idx_db_ = null;
      df.errback(opt_err);
    } else {
      goog.asserts.assertObject(db, 'db');
      me.idx_db_ = db;
      me.idx_db_.onabort = function(e) {
        goog.log.finest(me.logger, me + ': abort');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };
      me.idx_db_.onerror = function(e) {
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log(e);
        }
        goog.log.finest(me.logger, me + ': error');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };

      /**
       * @this {null}
       * @param {IDBVersionChangeEvent} event event.
       */
      me.idx_db_.onversionchange = function(event) {
        // Handle version changes while a web app is open in another tab
        // https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#
        // Version_changes_while_a_web_app_is_open_in_another_tab
        //
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log([this, event]);
        }
        goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' +
            event.version);
        if (me.idx_db_) {
          me.idx_db_.onabort = null;
          me.idx_db_.onblocked = null;
          me.idx_db_.onerror = null;
          me.idx_db_.onversionchange = null;
          me.onVersionChange(event);
          if (!event.defaultPrevented) {
            me.idx_db_.close();
            me.idx_db_ = null;
            var e = new Error();
            e.name = event.type;
            me.onFail(e);
          }
        }
      };
      df.callback(parseFloat(old_version));
    }

  }
663393
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {};
	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = options[i];
	            }
	        }

	        dbInfo.keyPrefix = dbInfo.name + '/';

	        if (dbInfo.storeName !== self._defaultConfig.storeName) {
	            dbInfo.keyPrefix += dbInfo.storeName + '/';
	        }

	        self._dbInfo = dbInfo;

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return Promise.resolve();
	        });
	    }
816874
function() {
        var self = this;

        if (typeof indexedDB === 'undefined' || typeof indexedDB.open === 'undefined') {
            console.error('IndexedDB API are not available in this browser.');
            return;
        }

        var dbVersion = 1;
        var dbName = this.dbName || location.href.replace(/\/|:|#|%|\.|\[|\]/g, ''),
            db;
        var request = indexedDB.open(dbName, dbVersion);

        function createObjectStore(dataBase) {
            dataBase.createObjectStore(self.dataStoreName);
        }

        function putInDB() {
            var transaction = db.transaction([self.dataStoreName], 'readwrite');

            if (self.videoBlob) {
                transaction.objectStore(self.dataStoreName).put(self.videoBlob, 'videoBlob');
            }

            if (self.gifBlob) {
                transaction.objectStore(self.dataStoreName).put(self.gifBlob, 'gifBlob');
            }

            if (self.audioBlob) {
                transaction.objectStore(self.dataStoreName).put(self.audioBlob, 'audioBlob');
            }

            function getFromStore(portionName) {
                transaction.objectStore(self.dataStoreName).get(portionName).onsuccess = function(event) {
                    if (self.callback) {
                        self.callback(event.target.result, portionName);
                    }
                };
            }

            getFromStore('audioBlob');
            getFromStore('videoBlob');
            getFromStore('gifBlob');
        }

        request.onerror = self.onError;

        request.onsuccess = function() {
            db = request.result;
            db.onerror = self.onError;

            if (db.setVersion) {
                if (db.version !== dbVersion) {
                    var setVersion = db.setVersion(dbVersion);
                    setVersion.onsuccess = function() {
                        createObjectStore(db);
                        putInDB();
                    };
                } else {
                    putInDB();
                }
            } else {
                putInDB();
            }
        };
        request.onupgradeneeded = function(event) {
            createObjectStore(event.target.result);
        };
    }
1338497
function initDB () {
  return db.listDatabases()
    .then(response => {
      if (response.data.indexOf(dbName) !== -1) {
        // database already exists
        return Promise.resolve('ok')
      } else {
        // create new database
        return db.createDatabase(dbName).then(() => 'ok')
      }
    })
}
878981
def load(self, key=None):
        # type: (Hashable) -> Promise
        
        if key is None:
            raise TypeError(
                (
                    "The loader.load() function must be called with a value,"
                    + "but got: {}."
                ).format(key)
            )

        cache_key = self.get_cache_key(key)

        # If caching and there is a cache-hit, return cached Promise.
        if self.cache:
            cached_promise = self._promise_cache.get(cache_key)
            if cached_promise:
                return cached_promise

        # Otherwise, produce a new Promise for this value.

        promise = Promise(partial(self.do_resolve_reject, key))  # type: ignore

        # If caching, cache this promise.
        if self.cache:
            self._promise_cache[cache_key] = promise

        return promise
258409
function saveIndexInfo() {

    // reset the cache
    var tmpCache = cache.idxInfo;
    cache.idxInfo = {};

    var promises = [];

    // add promise for each things being saved/updated
    _.each(tmpCache, function (idxInfo, key) {
        var where = { str: key };
        var select = '_id count';

        var promise = IdxInfoModel.findOne(where, select).exec()
            .then(function (savedItem) {
                if (savedItem) {
                    return IdxInfoModel.findOneAndUpdate(where, { $inc: { count: idxInfo.count }});
                }
                else {
                    var model = new IdxInfoModel(idxInfo);
                    var deferred = Q.defer();
                    model.save(function (modelErr) {
                        modelErr ? deferred.reject(modelErr) : deferred.resolve(model.toObject());
                    });
                    return deferred.promise;
                }
            });

        promises.push(promise);
    });

    return Q.all(promises);
}
877888
function() {
        console.log(
            `LocalIndexedDBStoreBackend: loading account data...`,
        );
        return Promise.try(() => {
            const txn = this.db.transaction(["accountData"], "readonly");
            const store = txn.objectStore("accountData");
            return selectQuery(store, undefined, (cursor) => {
                return cursor.value;
            }).then((result) => {
                console.log(
                    `LocalIndexedDBStoreBackend: loaded account data`,
                );
                return result;
            });
        });
    }
536964
function (db, query, callback) {
    // query parameter is optional
    if (!callback) {
      callback = query
      query = {}
    }

    // create a new request object
    var req = {
      // db name
      db: db,
      // authenticated url to db
      db_url: url.resolve(couch_url, encodeURIComponent(db)),
      // used by the update queue workers
      callback: callback,
      // store the query parameters
      query: query
    }

    // make sure the request has a since parameter set
    exports.updateSince(req, function (err, req) {
      if (err) {
        return callback(err)
      }

      // add the changes request to the pool
      exports.addToPool(idle, req)
    // queue the new request for immediate update
    // exports.refreshDB(updated, idle, db)
    })
  }
508630
function (fn) { var cache = {}
        return function (value, then) {
            if (value in cache) {                   //  there's a flaw: cache updates after fetch completes, so while fetch is running,
                then (cache[value]) }               //  any subsequent call (until cache is ready) will trigger fetch (as it doesnt know that result is already fetching)
            else {
                fn.call (this, value, function (result) {
                    then (cache[value] = result) }) } } }
1215654
function clear(dbid) {
  return new Promise((resolve, reject) => {
    return instance[dbid].then(db => {
      const req = db.transaction(db.name, 'readwrite')
          .objectStore(db.name).clear();
        req.onsuccess = () => resolve();
        req.onerror = event => reject(event);
    });
  });
}
192248
function (indexName, key) {
    return new Promise((resolve, reject) => {
      if (index[indexName]) {
        resolve(index[indexName][key] || null);
      } else {
        debug("opening index %s", indexName);
        storage.openIndex(indexName).then(index => {
          index[indexName] = index;
          resolve(index[indexName][key] || null);
        });
      }
    });
  }
391778
function eventPromiseCache(source, cacheProp, eventName, fn) {
  if (!source[cacheProp]) {
    source[cacheProp] = {}
  }

  const cache = source[cacheProp]
  if (!cache[eventName]) {
    cache[eventName] = new Promise((resolve, reject) => {
      function deleteAnd(fn) {
        // delete wrapper
        return result => {
          delete cache[eventName]
          fn(result)
        }
      }

      fn(deleteAnd(resolve), deleteAnd(reject))
    })
  }

  return cache[eventName]
}
790596
function init(config) {
    var promises = [];

    if (config.redis) {
        _.each(config.redis.dbs, function (idx, name) {
            promises.push(
                connectToRedis(idx, config.redis)
                    .then(function (remoteCache) {
                        caches[name] = wrapRemoteCache(remoteCache);
                        return true;
                    })
            );
        });
    }

    // initialization done once all connections established
    return Q.all(promises)
        .then(function () {
            return config;
        });
}
794132
def _ensure_index_cache(self, db_uri, db_name, collection_name):
        """"""
        if not self._check_indexes or db_uri is None:
            return {'indexes': None}
        if db_name not in self.get_cache():
            self._internal_map[db_name] = {}
        if collection_name not in self._internal_map[db_name]:
            indexes = []
            try:
                if self._index_cache_connection is None:
                    self._index_cache_connection = pymongo.MongoClient(db_uri,
                                                                       document_class=OrderedDict,
                                                                       read_preference=pymongo.ReadPreference.PRIMARY_PREFERRED)

                db = self._index_cache_connection[db_name]
                indexes = db[collection_name].index_information()
            except:
                warning = 'Warning: unable to connect to ' + db_uri + "\n"
            else:
                internal_map_entry = {'indexes': indexes}
                self.get_cache()[db_name][collection_name] = internal_map_entry
        return self.get_cache()[db_name][collection_name]
1236623
function(e) {
      goog.log.error(me.logger, 'SQLError ' + e + ' ' + e.code + '(' + e.message + ') ' +
          'while changing version from ' + db.version + ' to ' + new_version +
          ' on ' + dbname);
      if (ydn.db.con.WebSql.DEBUG) {
        goog.global.console.log(e);
      }
      throw e;
    }
639871
function () {
    return new Promise((resolve, reject) => {
      var startTime = Date.now();
      var size = fs.statSync(dataFile).size;
      var next = (readInfo, position) => {
        var jobs = [readNextChunk(readInfo)];

        if (position) {
          jobs.push(readAndIndex(position, readInfo.readBuffer));
          debug(position);
        }

        Q.all(jobs).then(results => {
          var nextReadInfo = results[0];
          var nextPosition = results[1] || {};

          readInfo.readBuffer = null;

          if (nextReadInfo.done && position) {
            debug("indexSize size: %s", (indexSize / 1024) + "KB");
            debug("index ready (took %s secs)", (Date.now() - startTime) / 1000);

            meta.size = indexSize;

            debug(meta);

            resolve();
          } else {
            next(nextReadInfo, nextPosition);
          }
        }).catch(err => reject(err));
      };

      debug("creating index");
      next({ size: size, fd: openDataFile() });
    });
  }