2013-03-05 4 views
0

Jaydata를 HTML5 indexedDB 용 API로 사용하고 있습니다. 재귀 적으로 쿼리해야하는 indexedDB에 테이블이 있습니다. 전체 프로세스가 완료되면 콜백이 필요합니다. 다음은 재귀 함수입니다. 모든 일이 끝나면 콜백이 필요합니다.재귀 비동기 호출에서 콜백 처리

function getData(idValue) { 
    myDB.MySplDB 
     .filter(function(val) { 
      return val.ParentId == this.parentId; 
     }, {parentId: idvalue}) 
     .toArray(function(vals) { 
      if(vals.length < 1) { 
       // some operation to store the value 
      } else { 
       for (var j=0;j<vals.length;j++) { 
        getData(vals[j].Id); 
       } 
      } 
     }); 
} 

가 완료되기 전에 호출되는 이후 .toArray.done(function(){...});이 작동하지 않습니다 추가.

답변

1

(면책 조항 : 나는 JayData을 위해 일)

전체의 마무리를 기다리는 프로세스를 사용하려면 약속을 사용해야합니다. 당신은 언제나 약속을해야합니다. 루프에서 그것은 까다로워지고, 슈퍼 약속을 되 찾는다.

function getData(idValue) { 
    return myDB.MySplDB 
    .filter(function(val) { 
     return val.ParentId == this.parentId; 
    }, {parentId: idvalue}) 
    .toArray(function(vals) { 
     if(vals.length < 1) { 
      // some operation to store the value 
      // important: return a promise from here, like: 
      return myDB.saveChanges(); 
     } else { 
      var promises = []; 
      for (var j=0;j<vals.length;j++) { 
       promises.push(getData(vals[j].Id)); 
      } 
      return $.when.apply(this, promises); 
     } 
    }); 
} 

getData(1) 
.then(function() { 
     // this will run after everything is finished 
}); 

말 : 그래서 코드는 다음과 같이해야 당신이 jQuery를 1.8 이상이 필요합니다, 그래서

  1. 이 예제는 jQuery를 약속을 사용 $ .when 우리가 적용해야 할 따라서 가변 인자를 사용

  2. 이 약간 다른 구문 Q 약속과 함께 작업 할 수

+0

에서 섹션'// 값을 저장할 몇 가지 연산', 나는 DB에 값을 저장하지 않습니다. 나는 이것을 배열에 저장하고있다. 의도는 자식이없는 모든 요소를 ​​얻는 것입니다. 즉, 개체의 ID는 다른 개체의 부모 ID가 아닙니다. – Prabhat

+0

'return myDB.saveChanges(); 대신에 무엇을 반환해야합니까? 'DB에 값을 저장하지 않으면? – Prabhat

+0

그런 경우 return true와 같은 것을 반환 할 수 있습니다. –

0

이 의사 코드는 귀하의 경우에 적합한가요?

var helper = function (accu) { 
// Take an id from the accumulator 
// query the db for new ids, and in the db query callback : 
    // If there is child, do "some operation to store the value" (I'm not sure what you're trying to do here 
    // Else add the child to the accumulator 
    // if accu is empty, call the callback, it means you reached the end 

GetData의()는 최초의 ID를 포함하는 누적 및 최종 콜백이 도우미를 부를 것이다