Merge pull request #604 from amark/rh

Better waiting for IndexedDB ready.
This commit is contained in:
Mark Nadal 2018-08-31 16:00:46 -07:00 committed by GitHub
commit 64ab915ef0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 11 deletions

View File

@ -11,7 +11,7 @@
opt.code.from = opt.code.from || '!';
function ename(t){ return encodeURIComponent(t).replace(/\*/g, '%2A') }
map = Gun.obj.map;
var map = Gun.obj.map;
if(!opt.store){
return Gun.log("ERROR: Radisk needs `opt.store` interface with `{get: fn, put: fn (, list: fn)}`!");

View File

@ -34,11 +34,7 @@
store.put = function(file, data, cb){
cb = cb || function(){};
if(!db){
var es = 'ERROR: RAD IndexedDB not yet ready.'
console.log(es);
cb(es, undefined);
} else {
var doPut = function(){
// Start a transaction. The transaction will be automaticallt closed when the last success/error handler took no new action.
var transaction = db.transaction([opt.file], 'readwrite');
@ -60,15 +56,20 @@
cb(es, undefined);
};
}
if(!db){
waitDbReady(doGet, 100, function(){
var es = 'ERROR: Timeout: RAD IndexedDB not ready.';
console.log(es);
cb(es, undefined);
}, 10)
} else {
doPut();
}
};
store.get = function(file, cb){
cb = cb || function(){};
if(!db){
var es = 'ERROR: RAD IndexedDB not yet ready.';
console.log(es);
cb(es, undefined);
} else {
var doGet = function(){
// Start a transaction. The transaction will be automaticallt closed when the last success/error handler took no new action.
var transaction = db.transaction([opt.file], 'readwrite');
@ -90,6 +91,31 @@
cb(es, undefined);
};
}
if(!db){
waitDbReady(doGet, 100, function(){
var es = 'ERROR: Timeout: RAD IndexedDB not ready.';
console.log(es);
cb(es, undefined);
}, 10)
} else {
doGet();
}
};
var waitDbReady = function(readyFunc, checkInterval, timeoutFunc, timeoutSecs){
var startTime = new Date();
var checkFunc = function(){
if(db){
readyFunc();
} else {
if((new Date() - startTime) / 1000 >= timeoutSecs){
timeoutFunc();
} else {
setTimeout(checkFunc, checkInterval);
}
}
};
checkFunc();
};
return store;