全部完成时递归“Fetch API”回调

时间:2017-09-06 22:05:49

标签: javascript jquery ajax

我的代码:

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解析为数组的函数。我无法编辑此功能。

它运行正常,但我在加载所有数据时进行回调时遇到问题。我正在寻找最好的解决方案。

1 个答案:

答案 0 :(得分:2)

如果您返回您创建的所有承诺,并将其提供给Promise.all,那么您的主函数调用将返回一个承诺,该承诺将在所有承诺解决时解决:

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是什么,以及您如何使用它,但我确实想知道这是否是您所需要的,因为{{1}将移动现有的数组元素,当它们的索引大于此处给出的索引时。考虑改为:

splice
相关问题