繁体   English   中英

RSVP承诺:then()链返回链的第一个值

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

我目前正在尝试将一些indexedDB代码包装到promise中。

我有一个“加载数据库”功能为:

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

我的意图是在第一个调用的DB函数上加载db,保存对它的引用,并在后续请求中重用它。

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);

}

最后,尝试使用上面创建的包装器:

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

最终, data包含db.load满足的值,而不是db.query满足的值。 我该如何解决? 有没有更好的方法可以实现相同的目标?

您似乎误解了“承诺”一词的含义。 一个承诺不是一个“任务”,它不能像函数可以执行或调用。 一个promise确实表示某个动作的(异步) 结果 ,它是一个函数的返回值

如果要在需要时调用“加载数据库”函数,请将其设为函数 (返回诺言),而不是诺言。 如果您向then传递了一个回调, then传递一个函数 ,而不是一个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 );
            }
        });
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM