所以我有一個索引資料庫這個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');
但現在,因爲一切都可以開始在不可預知的時刻/結束(取決於計算機的性能,數據庫大小,等等,等等。 。)我該如何處理所有那些保持代碼優美和可讀性的異步性?
完美!正是我一直在尋找的!我很高興給你你的第一個25分;) – meeDamian