在递归异步调用中处理回调
问题描述:
我使用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
不起作用,因为它被完成之前调用。
答
(声明:我JayData工作)
要等待整个的结束过程中你需要使用承诺。你总是必须回报一个承诺。在循环中变得棘手,返回超级承诺。因此,代码应该是这样的:
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
});
备注:
这个例子使用jQuery的承诺,所以你需要的jQuery 1.8+ $。当使用可变参数,因此我们需要的应用
这可以带q承诺工作有稍微不同的语法
答
这个伪代码在你的情况下是否有意义?
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蓄能器,并最终回调
在部分// //存储值的一些操作,我不会将值存储在数据库中。我将这些存储在一个数组中。目的是获得所有没有孩子的元素,即对象的Id不是任何其他对象的parentId。 – Prabhat 2013-03-05 15:30:36
还有什么我必须返回而不是'return myDB.saveChanges(); '如果我没有将值存储在数据库中? – Prabhat 2013-03-05 15:38:25
在这种情况下,您可以返回任何内容,例如返回true; – 2013-03-05 15:46:10