我无法单独解决这个问题,需要您的帮助。我正在使用 phonegap 应用程序中的嵌套主干对象,并希望将它们全部保存。保存时,我想显示加载动画。保存所有内容后,我想继续下一页/步骤。我已经实现了这一点,但是动画不起作用,因为我的保存循环阻止了所有 UI 更新。(我保存到 localStorage,而不是通过 ajax。)所以我试图通过在保存每个项目之间插入超时来减慢保存速度。现在保存被延迟了,但是在真正保存所有内容之前,界面会继续到下一页。我的回调似乎设置不正确。
你知道干净的嵌套回调的模式吗?
我整理了一个小提琴来说明我的问题。
您能帮我修复它,以便它以正确的顺序创建警报:A1, A2, A3, A4, A5, A6, A7, B1, B2, B3, Everything is finished
提前非常感谢。
如果您不想查看小提琴,这里是代码:
var forest = {
"trees": [{
"id": "tree A",
"leaves": [{
"name": "A1"
}, {
"name": "A2"
}, {
"name": "A3"
}, {
"name": "A4"
}, {
"name": "A5"
}, {
"name": "A6"
}, {
"name": "A7"
}]
}, {
"id": "tree B",
"leaves": [{
"name": "B1"
}, {
"name": "B2"
}, {
"name": "B3"
}]
}]
};
var callback = function () {
alert("Everything is finished");
};
var workOnTree = function (tree, callback) {
var leaves = tree.leaves;
var leafCount = 0;
var delayedAlert = function () {
alert(leaves[leafCount].name);
leafCount += 1;
if (leafCount < leaves.length) {
setTimeout(delayedAlert, 1000);
} else {
if (callback !== undefined && typeof callback == 'function') {
callback();
}
}
};
setTimeout(delayedAlert, 1000);
};
var workOnForest = function (forest, callback) {
var trees = forest.trees;
var treeCount = 0;
var delayedExecution = function () {
if (treeCount == (trees.length - 1)) {
// for last tree pass callback
workOnTree(trees[treeCount], callback);
} else {
workOnTree(trees[treeCount]);
}
treeCount += 1;
if (treeCount < trees.length) {
// this gives a delay between the trees
setTimeout(delayedExecution, 1000);
}
};
setTimeout(delayedExecution, 1000);
};
workOnForest(forest, callback);