2017-04-20 79 views
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; 
    }); 
} 
+0

一種方式更容易港口這一代碼將ES2016 +'異步/ await'(這是剛剛與含糖善良少輝) - 只使用承諾(因此更好的瀏覽器兼容性)是一個涉及多一點 –

回答

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

利用認爲異步/ 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; 
}; 
+0

是,謝謝!我的問題是創建嵌套的Promise.all我認爲是非常冗長而不使用等待 – frx08