如何在javascript中检测递归异步调用的完成

时间:2012-11-19 23:02:36

标签: javascript asynchronous recursion

我正在使用以下代码从Web SQL数据库中获取分层数据:

...
function getResult(query, data, callback){
    db.transaction(function(tx) {
        tx.executeSql(query, data, function(tx, result) {
        callback(result);
        });
    });
}

function findChildren(id){
    getResult("SELECT * FROM my_table WHERE parent_id=?", [id], function(result){
        for (var i = 0, item = null; i < result.rows.length; i++) {
            item = result.rows.item(i);
            data.push(item);
            findChildren(item.id);
        }
    });
}
var data = Array();
getResult("SELECT * FROM my_table WHERE name like ?", ["A"], function(result){
    for (var i = 0, item = null; i < result.rows.length; i++) {
        item = result.rows.item(i);
        data.push(item);
        findChildren(item.id);
    }
});
...

如何检测执行是否已完成?

1 个答案:

答案 0 :(得分:3)

使用findChildren的回调和开放交易的计数器:

function findChildren(id, callback){
    getResult("SELECT * FROM my_table WHERE parent_id=?", [id], function(result){
        var results = [],
            results.finished = 0;
            len = result.rows.length;
        for (var i = 0; i < len; i++) (function(i) {
            var item = result.rows.item(i);
            ...
            ...
            findChildren(item.id, function(result) {
                results[i] = result;
                if (++results.finished == len)
                    callback(results);
            });
        })(i);
    });
}

getResult("SELECT * FROM my_table WHERE name like ?", ["A"], function(result){
    var results = [],
        results.finished = 0, 
        len = result.rows.length;
    for (var i = 0; i < len; i++) (function(i) {
        var item = result.rows.item(i);
        ...
        ...
        findChildren(item.id, function(result) {
            results[i] = result;
            if (++results.finished == len) {
                // now results contains a nice tree of arrays with children ids
                // do something with it
            }
        });
    })(i);
});

Promises将抽象计数器并简化回调处理。此外,由于您的两个查询非常相似,您可能也希望在一个通用函数中抽象它们。