1
嗨那裏我有以下python遞歸函數,從所有子節點求和值,我想在NodeJS中端口,但我有一些異步調用的問題。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
我試圖做到這一點,但我可能需要與承諾鏈,因爲總次數不可用,而我循環,因爲我得到它從一個異步函數
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 +'異步/ await'(這是剛剛與含糖善良少輝) - 只使用承諾(因此更好的瀏覽器兼容性)是一個涉及多一點 –