【问题标题】:Return all values from indexedDB database objectStore从 indexedDB 数据库 objectStore 返回所有值
【发布时间】:2013-11-14 13:25:51
【问题描述】:

只需尝试编写一个“selectAll”方法,该方法将 objectStore 名称作为参数并返回其包含的所有键/值对,而不是简单地在对象存储的每次迭代中运行回调。

本质上,在执行 indexedDB 事务时模仿同步行为。

var results = []

request.onsuccess = function(e) {

    var result = e.target.result;

    if (!result) {
        //I could call successcallback here with JUST this 'row' of data
        successCallback(result);
        return;
    }

    //I could push the results into an array here, but I would need to 'wait' until all the onSuccess methods have fired before returning it.
    results.push(result.value);
    result.continue();
}

我正在使用 Angular,我认为 Promise 可能是答案。特别是, $q.all() 在这种情况下会有所帮助吗?

【问题讨论】:

    标签: javascript angularjs indexeddb


    【解决方案1】:

    这实际上是一个比我想象的更简单的问题。我把上面的代码改成下面...

    function selectAll(model, successCallback) {
        ...
        request.onsuccess = function(e) {
    
            var result = e.target.result;
    
            if (result) {
                results.push(result.value);
                result.continue();
            } else {
                $rootScope.$apply(function() {
                    successCallback(results);
                });
            }
        }
    }
    

    我使用了successCallback作为参数,然后调用函数返回了一个promise给它的调用函数...

    db.selectAll(model, function(results) {
        deferred.resolve(results);
    })
    

    重要提示

    $rootScope.$apply(function() {
    

    在使用 Angular 时围绕回调调用。

    【讨论】:

    • 另一种可能性是使用事务对象的 oncomplete 回调。
    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2023-04-03
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多