jensarps/IDBWrapper

to add an ability to use deferred objects

Opened this issue · 2 comments

Here is usage example:

var dude = {
  firstname: 'John',
  lastname: 'Doe',
  age: 52,
  emails: [
    'johndoe@example.com',
    'jd@example.com'
  ]
};

var onsuccess = function(id){
  console.log('Yeah, dude inserted! insertId is: ' + id);
}
var onerror = function(error){
  console.log('Oh noes, sth went wrong!', error);
}

customers.put(dude).done(onsuccess).fail(onerror)
$.when(customers.put(dude), customers.put(dude), customers.put(dude)).done(function() {alert('awesome');});

Yep, true, that'd be awesome, and I'd love to have this.

I haven't implemented this yet due to the complex situation of Promise implementations. I didn't want to ship my own implementation with this project, because ppl might already be using another implementation like Q or jQuery's Deferred, or another of the dozens of projects out there.

To cope with this, I initially wanted to build wrappers for popular libraries and started with jQuery (it's over here: https://github.com/jensarps/idbwrapper-utils/tree/master/idbpromises-jquery). However, I didn't progress there.

Now with native Promises on their way, this might be the way to go. As this will change the return signature of methods, thus breaking backwards compatibility, this will lead to IDBWrapper 2.0.

I'll leave this open until implemented.

isao commented

FWIW, one can wrap IDBWrapper's methods to return Promises, and maintain it parallel. Here's a simplified partial example in TypeScript:

class IdbDao<T> {
    protected ready: Promise<void>;
    protected idb: typeof IDBStore; // https://github.com/jensarps/IDBWrapper

    constructor(options: IDb.Schema<T>) {
        this.ready = new Promise<typeof IDBStore>((resolve, reject) => {
            this.idb = new IDBStore({
                ...options,
                onStoreReady: resolve,
                onError: reject,
            });
        });
    }

    putBatch(records: T[]): Promise<IDBTransaction> {
        return this.ready.then(() =>
            const tx = new Promise<IDBTransaction>((resolve, reject) => this.idb.putBatch(records, () => resolve(tx), reject))
        );
    }