How to detect completion of recursive asynchronous calls in javascript

只愿长相守 提交于 2019-12-23 10:17:06

问题


I am using following code to fetch hierarchical data from Web SQL Database:

...
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);
    }
});
...

How can I detect if the execution has been completed?


回答1:


Use a callback for findChildren and a counter for open transactions:

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 will abstract the counter and simplify the callback handling. Also, as your two queries are very similiar, you might want to abstract them in a common function, too.



来源:https://stackoverflow.com/questions/13463943/how-to-detect-completion-of-recursive-asynchronous-calls-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!