2010-06-03 2 views
1

안녕하세요, 저는 비동기식 디자인 패턴을 잘 다루지 않았으며, 두 개의 비동기 데이터 가져 오기를 수행하는 스크립트를 작성하는 데 문제가있었습니다.Dojo 가져 오기, 동시에 두 개의 비동기 페치를 기다리는 방법?

Im Dojo.data.api.Read.Fetch()를 사용하여 별도의 데이터베이스에서 두 fetch()를 호출합니다. 문제는 비동기 적으로 다시 발생합니다. 그러나, 나는 비동기 가져 오기가 완료되면 내 스크립트를 계속하려면 결과를 참조해야합니다. 나는 이것을 어떻게하는지 모른다. 그리고 그 안에 문제가있다.

나는의 가져 오기 onComplete를 필드의가 알고 및 사용 방법,하지만 난 볼 수있는 최상의 경우 솔루션은 두 번째 가져올 첫 번째의 onComplete를에 가져 호출 할 수있다. 나는이 가져 오기를 동시에하고 싶습니다 . 이것을 할 수있는 방법이 있습니까?

여기에 설명을 위해 내 프로그램의 현재 구조입니다 :

this.dict1.fetch({query:"blahblahblah", onComplete: function(items) { something here? }});
this.dict2.fetch({query:"blahblahbleh", onComplete: function(items) { or maybe something here? }});
this.orMaybeDoSomethingAfterBothFetches()

어떤 도움을 크게 감상 할 수있다! here를 참조 -

답변

1
// this is a variation of a function I have answered quite a few similar questions on SO with 
function collected(count, fn){ 
    var loaded = 0; 
    var collectedItems = []; 
    return function(items){ 
     collectedItems = collectedItems.concat(items); 
     if (++loaded === count){ 
      fn(collectedItems); 
     } 
    } 
} 

var collectedFn = collected(2, function(items){ 
    //do stuff 
}); 


this.dict1.fetch({query:"blahblahblah", onComplete: collectedFn); 
this.dict2.fetch({query:"blahblahbleh", onComplete: collectedFn); 

대체 솔루션 당신은 페치의 각 dojo.Deferreds를 만든 다음 dojo.DeferredList을 사용하고에 deferreds를 추가 할 수

var store = { 
    exec: function(){ 
     if (this.items1 && this.items2) { 
      // do stuff with this.items1 and this.items2 
     } 
    } 
}; 

this.dict1.fetch({query:"blahblahblah", onComplete: function(items) { 
    store.items1 = items; 
    store.exec(); 
}); 
this.dict2.fetch({query:"blahblahbleh", onComplete: function(items) { 
    store.items2 = items; 
    store.exec(); 
}); 
+0

나는 좋아한다. – Dfowj

2

입니다. 이 솔루션을 사용하면 호출 할 함수 목록에 'n'함수를 추가 할 수 있습니다. 또한 모든 dojo.Deferred 콜백 및 errBack 기능을 이용합니다.

var fetch1 = new dojo.Deferred(); 
fetch1.addCallback(this.dict1.fetch...); 
var fetch2 = new dojo.Deferred(); 
fetch2.addCallback(this.dict2.fetch...); 

var allFuncs = new dojo.DeferredList([fetch1, fetch2]); 
var doStuffWhenAllFuncsReturn = function() {...}; 
allFuncs.addCallback(doStuffWhenAllFuncsReturn); 
+0

내가 이것에 대해 이해하지 못하는 한가지는 fetch를 Delferred 생성자를 호출하는 값으로 사용하는 것입니다. 그게 어떻게 작동하는지 설명하는주의? – Dfowj

+0

정확합니다. 위의 수정 된 코드를 참조하십시오. 1.5에서 API가 변경된 것처럼 보이므로 모든 새로운 약속 기반 API와 dojo.when를 살펴볼 수 있습니다. – Andy

관련 문제