您好我有以下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
我试图这样做,但我可能需要用promises链接它,因为当我从异步函数中获取它时循环时总计数不可用
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;
});
}
答案 0 :(得分:1)
没有看到getAsyncValue
我无法提供完整的答案 - 但是
var getAsyncValue = function(id) {
return new Promise((resolve, reject) => {
// resolve some value some how
});
};
// helper to make the getTree function "nicer"
c.allAsync = function(str) {
return new Promise((resolve, reject) =>
this.all(str, (err, children) => {
if (err) {
return reject(err);
}
resolve(children);
})
);
};
var getTree = function(parent_id, level=1) {
return c.allAsync("select * from users where parent_id="+parent_id).then(children =>
Promise.all(children.map(child =>
Promise.all([getAsyncValue(child.id), getTree(child.id, level+1)])
.then(([a, b]) => a + b)
)).then(results => results.reduce((a, b) => a + b))
);
};
我认为使用async / await,代码可以写成:
var getAsyncValue = async function(id) {
return new Promise((resolve, reject) => {
// resolve some value some how
});
};
// helper to make the getTree function "nicer"
c.allAsync = async function(str) {
return new Promise((resolve, reject) =>
this.all(str, (err, children) => {
if (err) {
return reject(err);
}
resolve(children);
})
);
};
var getTree = async function(parent_id, level=1) {
let children = await c.allAsync("select * from users where parent_id="+parent_id);
let total = 0;
for (let i = 0; i < children.length; i++) {
let child = children[i];
total += await getAsyncValue(child.id);
total += await getTree(child.id, level + 1);
}
return total;
};