所以我有这个 JS indexedDB 库:
window.db = {
name:"indexedDBname",
varsion:0.7,
_settings:"indexedDBobject",
h:null, // Handler to the db
open:function(callback,callback1) {
var r = indexedDB.open( db.name );
r.onupgradeneeded = function(e){ console.log(".onupgradeneeded is not yet supported by webkit"); };
r.onsuccess = function(e){
db.h = e.target.result;
if( db.version !== db.h.version ) {
var v = db.h.setVersion( db.version );
v.onsuccess = function(e) {
if(db.h.objectStoreNames.contains( db._settings )) db.h.deleteObjectStore( db._settings );
db.h.createObjectStore(db._settings, { keyPath:"name" });
};
v.onfailure = db.onerror;
v.onerror = db.onerror;
v.onblocked = db.onerror;
}
// CALLBACKS
if(typeof callback=="function" && typeof callback1=="function") callback.call(window,callback1);
else if(typeof callback=="function" && typeof callback1!="function") callback.call(window);
};
r.onfailure = db.onerror;
},
getSettings:function(callback){ // retrieve user custom settings
var t = db.h.transaction( [db._settings], IDBTransaction.READ_ONLY ),
s = t.objectStore(db._settings),
keyRange = IDBKeyRange.lowerBound(0),
cursorRequest = s.openCursor(keyRange),
tmp = {};
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result==false) {
// CALLBACKS
if(typeof callback=="function") callback.call(window);
return;
}
tmp[result.value.name] = result.value.value;
result.continue();
}
cursorRequest.onerror = db.onerror;
},
onerror:function(e){ console.log("Handle and print error here:"+e); }
};
// actual run
db.open( db.getSettings, user.applySettings);
我经常使用它,但正如你所看到的,那些回调看起来不太好......当我想做一系列任务甚至用它们自己的参数集调用这些函数中的任何一个时,我的代码开始看起来很不稳定,例如。
db.open('forWhichUser',newSettingsToApplyObject, callback1, argumentForCallback1, secondOptionalArgument, callback2, etc);
所以在过去,我会这样做:
db.open('userName', settingsMap);
var opts = db.getSettings();
user.downloadInfoBasedOn( opts );
user.renderInfoTo('userDataHolderId');
但是现在,由于一切都可以在不可预测的时刻开始/结束(取决于计算机性能、数据库大小等),我该如何处理所有这些异步性,以保持代码的优雅和可读性?