1

我使用 Jaydata 作为 HTML5 indexedDB 的 API。我在 indexedDB 中有一个需要递归查询的表。整个过程完成后我需要回调。以下是递归函数。一切完成后我需要回调。

function getData(idValue) {
    myDB.MySplDB
        .filter( function(val) {
            return val.ParentId == this.parentId;
        }, {parentId: idvalue})
        .toArray( function(vals) {
            if(vals.length < 1) {
                // some operation to store the value
            } else {
                for (var j=0;j<vals.length;j++) {
                    getData(vals[j].Id);
                }
            }
        });
}

添加.done(function(){...});.toArray不起作用,因为它在完成之前被调用。

4

2 回答 2

1

(免责声明:我为 JayData 工作)

要等待整个过程的完成,您需要使用 Promise。你总是要回报一个承诺。在循环中它变得棘手,返回一个超级承诺。所以代码应该是这样的:

function getData(idValue) {
    return myDB.MySplDB
    .filter( function(val) {
        return val.ParentId == this.parentId;
    }, {parentId: idvalue})
    .toArray( function(vals) {
        if(vals.length < 1) {
            // some operation to store the value
            // important: return a promise from here, like:
            return myDB.saveChanges(); 
        } else {
            var promises = [];
            for (var j=0;j<vals.length;j++) {
                promises.push(getData(vals[j].Id));
            }
            return $.when.apply(this, promises);
        }
    });
}

getData(1)
.then(function() {
        // this will run after everything is finished
});

评论:

  1. this example uses jQuery promises, so you'll need jQuery 1.8+ $.when uses varargs hence we need the apply

  2. this can work with q promise with a slightly different syntax

于 2013-03-05T14:52:43.780 回答
0

这个伪代码在你的情况下有意义吗?

var helper = function (accu) {
 // Take an id from the accumulator
 // query the db for new ids, and in the db query callback : 
   // If there is child, do "some operation to store the value" (I'm not sure what you're trying to do here
   // Else add the child to the accumulator
   // if accu is empty, call the callback, it means you reached the end

getData() 将使用包含第一个 id 的累加器和您的最终回调调用此助手

于 2013-03-05T14:01:04.877 回答