6

我正在使用以下代码从 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);
    }
});
...

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

4

1 回答 1

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

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

于 2012-11-20T23:59:37.237 回答