2013-04-05 5 views
0

이 빵 부스러기 빌더를 작동 시키려면 약간의 도움이 필요합니다. 항목 배열을 리턴해야하는 상위 카테고리에 대한 재귀 적 페치입니다. 잘 작동하지 않고 뇌가 튀었습니다 .... 현재는 마지막 항목 만 반환합니다.재귀 콜백

var walk = function(c, done) { 
    var results = []; 
    Category.findById(c).exec(function(err, cat) { 
    if(cat) { 
     results.push({ title: cat.title, id: cat.id}); 
     if(cat.parent) { 
     walk(cat.parent, function(err, res) { 
      results = results.concat(res); 
     }); 
     } 
     return done(null, results); 
    } 
    done(results); 
    }); 
}; 

walk(product.categories[0].id, function(err, results) { 
// if (err) console.log (err); 
    console.log(results); 
}); 
+0

각 부모 고양이는 하나 뿐이며 고양이에게 부모가없는 경우 종료해야합니다. 완료 (결과)하기 전에 그냥 다른 사람이 있었지만 그 중 하나가 정확하지 않습니다 – cyberwombat

답변

0

좋아는 내부 도보 통화에서 수행 호출에 필요한 .... 그것을 얻었다.

var walk = function(c, done) { 
    var results = []; 
    Category.findById(c).exec(function(err, cat) { 
    if(cat) { 
     results.push({ title: cat.title, id: cat.id}); 
     if(cat.parent) { 
     walk(cat.parent, function(err, res) { 
      results = results.concat(res); 
      done(null, results); 
     }); 
     } else { 
     done(null, results); 
     } 
    } else { 
     done('No cat found'); // Error 
    } 
    }); 
}; 
0

불행히도 재귀 호출과 콜백은 모두 잘 어울리지 않습니다. 첫 번째 카테고리를 검색 한 후에 done으로 전화를 걸었으나 done으로 전화하기 전에 walk에 대한 다른 통화가 완료 될 때까지 기다리지 않아도됩니다. 그들을 기다려야합니다. 나는 이것 (의사 코드)과 같은 것을 할 것이다 :

fetch this category 
    if no subcategories 
     call callback with [{ title: ... }] and return 
    pending = number of subcategories 
    results = [[{ title: ... }]] 
    for each subcategory 
     recurse 
      pending-- 
      results[index + 1] = subcategory_results 
      if none pending 
       call callback with the concatenation of the subarrays of results 
+0

그는 스택 카운터를 추가 할 수 있으므로 가장 낮은 수준에서 한 번만 호출합니다. – scones

+0

@scones : 나는 네가하는 말을 잘 이해하지 못한다. 아마도 자신의 답변을 추가하고 싶습니까? – icktoofay