RSVP Promises: then() chain returning the first value of the chain

150 views Asked by At

I'm currently trying to wrap some indexedDB code into promises.

I have a "load db" function as:

db.load = new RSVP.Promise( function ( fulfill , reject ) {
    //...
    if (globaldb) {
        fulfill(globaldb);
        return;
    }
    //...
    request.onsuccess = function(e) {
        globaldb = e.target.result;
        fulfill(globaldb);
    }
});

My intent is to load the db the on the first DB function called, saving the reference to it and reusing it on subsequent requests.

db.query = function( objectStoreName , options ) {

    var queryPromise = new RSVP.Promise( function ( fulfill , reject ) {

        //... do some work
        transaction.oncomplete = function() {
            fulfill( anArray );
        }

    });

    return db.load.then(queryPromise);

}

Finally, trying to use the wrapper created above:

db.query("tablename", ... ).then( function ( data ) {
    //do things, write to the screen, etcetera
});

It ends up that data contains the value fulfilled by db.load, instead of the one fulfilled by db.query. How can I fix that? Is there a better way to achieve the same goal?

1

There are 1 answers

0
Bergi On

It seems you are misunderstanding what the term "promise" means. A promise is not a "task", it cannot be executed or called like a function can. A promise does represent the (asynchronous) result of some action, it is the return value of a function.

If you want a "load DB" function that is called when needed, make it a function (that returns a promise), not a promise. If you pass a callback to then, pass a function, not a promise.

var globaldb = null;
db.load = function() {
    if (globaldb) {
        return globaldb;
    } else {
        return globaldb = new RSVP.Promise( function ( fulfill , reject ) {
            //...
            request.onsuccess = function(e) {
                fulfill(e.target.result);
            };
        });
    }
};
db.query = function( objectStoreName , options ) {
    return db.load().then(function(conn) {
//                ^^               ^^^^
//         call it here!       the result of loading the database
        return new RSVP.Promise( function ( fulfill , reject ) {
            //... do some work
            transaction.oncomplete = function() {
                fulfill( anArray );
            }
        });
    });
};