Skip to content

Instantly share code, notes, and snippets.

@thgreasi
Last active August 29, 2015 14:26
Show Gist options
  • Save thgreasi/01f6460f35bf49213c0e to your computer and use it in GitHub Desktop.
Save thgreasi/01f6460f35bf49213c0e to your computer and use it in GitHub Desktop.
LocalForage setDriver Looper
async function setDriver(driverNames) {
for (var driverName of driverNames) {
if (this.supports(driverName) {
try {
let driver = await this.getDriver(driverName).then(driver => driver._initDriver());
if (driver) {
return Promise.resolve(driver);
}
} catch (e) { }
}
}
return Promise.reject('No supported driver found!');
}
var localForageDriverOrder = [localforage.INDEXEDDB, localforage.LOCALSTORAGE, localforage.WEBSQL];
var setDriverPromise = new Promise(function(resolve, reject) {
var drivers = localForageDriverOrder.slice();
var crntDriverPromise = Promise.resolve();
crntDriverPromise.then(driversPromiseLoop);
function driversPromiseLoop(){
var driver = null;
while (driver = drivers.shift()) {
if (localforage.supports(driver)) {
crntDriverPromise = localforage.setDriver(driver);
return crntDriverPromise.then(function(){
resolve();
}).catch(driversPromiseLoop);
}
}
reject('No driver');
}
});
new Promise((resolve, reject) => {
runGeneratorOnce(myPromiseGenerator, initialValue);
function runGeneratorOnce(pg, result) { var status = pg.next(result);
if (status.done) { reject('No driver'); return; }
status.value.then(resolve).catch(value => {
return runGeneratorOnce(pg, value);
});
}
function* myPromiseGenerator() {
for (var i = 0, len = drivers.length; i < len; i++) {
if (localforage.supports(driver)) {
yield localforage.setDriver(driver);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment