【发布时间】:2017-04-20 01:15:53
【问题描述】:
您好,我有以下 python 递归函数,它对所有子节点的值求和,我想在 NodeJS 中移植,但异步调用有一些问题。
def getTree(parent_id, level=1):
c.execute('select * from users where parent_id=?', (parent_id,))
rows = c.fetchall()
total = 0
for child in children:
total += getAsyncValue(child.id)
total += getTree(child.id, level+1)
return total
我尝试这样做,但我可能需要用 Promise 链接它,因为当我从异步函数中获取它时,总计数不可用
getTree = function(parent_id, level=1) {
c.all("select * from users where parent_id="+parent_id, function(err, children) {
var total = 0;
children.forEach(function(child) {
total += getAsyncValue(child.id)
total += getTree(child.id, level+1)
});
return total;
});
}
【问题讨论】:
-
更容易移植此代码的一种方法是 ES2016+
async/await(这只是带有甜味的 Promises)- 仅使用 Promise(因此更好的浏览器兼容性)涉及更多
标签: javascript python asynchronous recursion promise