IndexedDB一个库,从多个不同的地方调用,具有不同的回调

时间:2012-05-02 08:32:56

标签: javascript asynchronous callback chaining

所以我有这个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');

但现在,因为一切都可以在不可预测的时刻开始/结束(取决于计算机性能,数据库大小等等),我如何处理所有异步性保持代码优雅和可读?

1 个答案:

答案 0 :(得分:2)

您可以使用JavaScript promises / deferreds模式:

  1. http://wiki.commonjs.org/wiki/Promises/A
  2. http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx
  3. Promises / deferreds可以帮助您创建更容易和可读的异步代码。你可以使用jQuery deffered object来实现它(http://api.jquery.com/category/deferred-object/)

    另一种选择是使用story.js封装IndexedDB API并以更简单的方式公开它(http://blogs.microsoft.co.il/blogs/gilf/archive/2012/04/21/the -story-begins.aspx)

    我希望你会发现这个答案很有用。

    吉尔