2013-03-20 3 views
6

jQuery 1.9.1 약속에 문제가 있습니다. 잠재적으로 또 다른 지연을 반환하는 조건부 논리가 필요할 수 있으며 처리 방법이 확실하지 않습니다. 이것은 최선의 시도 였지만, 아래에 주석이 표시되어있을 때 else 브랜치를 눌렀을 때 나는 여전히 두 번째 .then() 함수를 사용하여 사용자에게 돌아갈 수 있기를 바라고 있습니다. 이러한 시나리오를 처리하는 방법에 대한 패턴은 무엇입니까?약속을 사용하여 분기 처리

storage.provision(c) 

.then(function(rc){ 
    if(rc === 0){ 
     storage.write(c); 
    }else{ 
     return options.onSuccess(rc); //how i got back to the users callbacks/promise, but this 
     //takes me to the .then below 
    } 
}) 
//storage.write returns a promise as well, do I do another .then 
// like this? 
.then(function(rc){ 
    //I was hoping this would catch, the storage.write() case, and it does, but it also catches 
    //the retun options.onSuccess(rc) in the else case. 
    options.onSuccess(rc); 
}) 


.fail(function(e){ 
    //handle error using .reject() 
}); 
+0

이 게시물은 도움이 될 수 있습니다 : http://stackoverflow.com/questions/12149993/attempting-to-break-jquery-promise-chain-with-then-fail-and-reject – mattytommo

+0

[This post] (http : //net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/) 약속 내용을 더 잘 이해하는 데 도움이됩니다. 일반적으로 조건문을 사용하려면 약속을 변수로 저장하고 조건 내에 '성공'또는 '실패'를 실행해야합니다. 그러면 다른 방법으로 수행하는 것처럼 보입니다. – acconrad

답변

4

이것은 options.onSuccess(rc);는하지만 결코 첫 번째에서 두 번째로 .then()에 무조건 실행되는 것을보기를 취함으로써 쉽게된다.

  • rc === 0 경우 storage.write(c)에 응답
  • 즉시 경우 rc !== 0 완료 :

    따라서, 제 .then() 어느 rc 전달한다. 자연스럽게 허용하려면 새 약속의 값이 done 콜백에서 반환 할 수 있기 때문에

.then()이 정말 편리합니다.

storage.provision(c).then(function(rc) { 
    if(rc === 0) { 
     var dfrd = $.Deferred(); 
     storage.write(c).done(function() { 
      dfrd.resolve(rc); 
     }).fail(dfrd.fail); 
     return dfrd.promise(); 
    } else { 
     return rc;//pass on rc to the second .then() 
    } 
}).then(function(rc){ 
    options.onSuccess(rc); 
}).fail(function(e){ 
    //handle error using .reject() 
}); 

나는 다른 접근법이 존재한다고 생각하지만 이것은 가장 근본적인 개념입니다. 그것은 좋은 것

rc === 0이 있지만, rc에 통과 이런 식으로 행동하는 storage.write()을 수정할 필요가 피하는 가장 현실적인 방법은 때 이연를 새로 만들 필요하지.

관련 문제