如何在javascript中检测递归异步调用的完成 [英] How to detect completion of recursive asynchronous calls in javascript
本文介绍了如何在javascript中检测递归异步调用的完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码从Web SQL数据库中获取分层数据:
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?
推荐答案
使用 findChildren
的回调和开放交易的计数器:
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将抽象计数器并简化回调处理。此外,由于您的两个查询非常相似,您可能也希望在一个常用函数中抽象它们。
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.
这篇关于如何在javascript中检测递归异步调用的完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文