2014-06-18 3 views
3

angular docs say 그럴 수 체인 약속을 거부 :이처럼 체인 약속을

promiseB = promiseA.then(function(result) { 
    return result + 1; 
}); 

는 함수 내에서 promiseB을 거부 할 수 있습니까?

피. 스.이 예에서 나는 promiseA이 항상 해석한다고 가정한다.

답변

3
promiseB = promiseA.then(function(result) { 
    if (result > 0) { 
     return result + 1; 
    } 
    else { 
     return $q.reject('whatever reason'); 
    } 
}); 

에서 촬영이 사인에게 promiseA의 성공 콜백의 반환 값을 작동 성공한 콜백의 반환 값으로 해결되거나 또 $q.reject으로 명시 적으로 거부하거나 예외를 throw하는 경우 거부되는 다른 약속으로 변환됩니다.

2

실제로 .then() 함수는 두 가지 콜백 함수를 사용할 수 있습니다. 하나는 성공을위한 것이고 다른 하나는 같은 문서에 지정된 오류입니다. 오류 처리기 콜백에서 $ q.reject()를 사용하여 약속을 거부 할 수 있습니다. 그렇게 말하지만, 당신은 또한 너무 성공 콜백에서 사용할 수 있습니다 :

promiseB = promiseA.then(function(result) { 
    // success: do something and resolve promiseB 
    //   with the old or a new result 

    if (!result || result !== "Whatever you're looking for") { 
     $q.reject("A Reason") 
    } // additional edit from me 

    return result; 
    }, function(reason) { 
    // error: handle the error if possible and 
    //  resolve promiseB with newPromiseOrValue, 
    //  otherwise forward the rejection to promiseB 
    if (canHandle(reason)) { 
    // handle the error and recover 
    return newPromiseOrValue; 
    } 
    return $q.reject(reason); 
    }); 

*Angular Documentation

+0

OP는 'promiseA'가 항상 해결된다고 가정하기 때문에 질문에 답하지 않습니다. – axelduch

+0

이 경우 성공 콜백에서 $ q.reject 만 사용할 수 있습니다. – JoshSGman