我的代码:
function genTree(parent_id) {
GetData('tableName', {
'parent': parent_id
}).then(function(features) {
var feature = null
for (var i = 0, total = features.length; i < total; i++) {
feature = features[i]
var temp = {}
var parentIndex = getIndexById(parent_id);
temp["ID"] = feature['ID']
temp["PARENT_ID"] = feature['PARENT_ID'] || 0
state.splice(parentIndex + (i + 1), 0, temp)
genTree(feature['ID']);
}
}).catch(function(e) {
console.log('Error', e)
})
}
getData() 是一个使用“Fetch API”并将响应 xml 解析为数组的函数。我无法编辑此函数。
它工作正常,但我在所有数据已加载的情况下进行回调时遇到问题。我正在寻找最好的解决方案。
最佳答案
如果您返回您创建的所有 Promise,并将它们提供给 Promise.all
,那么您的主函数调用将返回一个 Promise,该 Promise 将在所有问题都解决后解决:
function genTree(parent_id) {
return GetData('tableName', {
parent: parent_id
}).then(function(features) {
var parentIndex = getIndexById(parent_id);
return Promise.all(
features.map(function (feature, i) {
var temp = {
ID: feature.ID,
PARENT_ID: feature.PARENT_ID || 0
};
state.splice(parentIndex + (i + 1), 0, temp);
return genTree(feature.ID);
})
);
}).catch(function(e) {
console.log('Error', e);
})
}
现在你可以做:
genTree(parent_id).then(function () {
console.log('all done');
});
请注意,我没有碰 state.splice(parentIndex + (i + 1), 0, temp);
,因为不清楚 state
是什么,以及如何使用它,但我确实想知道这是否是您所需要的,因为当现有数组元素的索引大于索引时,splice
会将它们移动到右侧在这里给出。考虑这样做:
state[parentIndex + i + 1] = temp;
关于javascript - 全部完成后递归 "Fetch API"回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085000/