2016-07-04 3 views
0

약속과 함께 서버 호출의 동작을 구현하려고합니다.Javascript - 약속 후 리디렉션

서버에서 응답이 "성공"이면 "성공"페이지로 리디렉션하고 "실패"이면 "실패"페이지로 리디렉션하고 싶습니다.

현재 상황은 응답이 대기 중이 아니며 브라우저가 리디렉션 됨 보다 앞에 서버로부터 응답을 받지만 성공 또는 실패 여부는 중요하지 않습니다.

내가 뭘 잘못하고 있으며 어떻게 해결할 수 있습니까?

var ch_item; 
Payment.postInvoice(dataObj, $rootScope.usertoken).then(function(res){ 
    if (res.message === "success") { 
    setTimeout(function() { 
     var payment_details = res.data; 
     User.getUserById(res.data.stylist_uuid, res.data.customer_uuid).then(function (stylist) { 
     ch_item = TC_Service.getChatCredentials(stylistInfo.uid, $rootScope.userId, $rootScope.usertoken, dataObj.request_uuid); 
     openModelAlert("Thank you for your booking!"); 
     $location.path('/success'); 
     }); 
    }, 500); 
    } else { 
    setTimeout(function() { 
     openModal("Sorry, please come back later."); 
     $location.path('/failure'); 
    }, 500); 
    } 
    $modalInstance.dismiss('cancel'); 
    $location.path('/default'); 
}, function() { 
    console.log("Something went wrong with the payment, the response is: "+res.message); 
}); 

도움말 나를 사람 :

이 시간 내 주셔서 감사 ...

V.

+0

_ "내가 서버에서 모든 응답 도착하기 전에 브라우저가 리디렉션"'에 "/ 기본"'재인가 _를? '$ location.path ('/ default');의 목적은 무엇입니까? – guest271314

+0

두 번째 콜백은'res' 인수를 사용하지만 현재 인수를받지 않습니다. 실제로'err'이라는 인자를 두 번째 콜백에 추가하고'res' 대신에 그것을 사용해야합니다. 이것들은 인수의 이름 일 뿐이므로 원하는 것을 실제로 사용할 수 있습니다. 그러나, 규칙 상으로,'onRejected()'콜백은'err'이라는 인자를 취해야합니다. – fvgs

+0

응답 전에 확실합니까? 이것이 문제라면 약속은 작동하지 않으며이 코드는 아무 관계가 없습니다. 또한 각도 setTimeout을 사용하는 경우 각도로 동기화되지 않으므로 $ timeout을 사용하려고 할 수 있습니다. –

답변

1

반환 약속 : 여기

내 코드의 관련 부분입니다 호출이 실패했거나 성공했는지 판단하기 위해 if/else 문을 둘 필요가 없습니다. 이것은 기본 콜백의 일부입니다.

.then(
    function(response){ 
    //if success show the response in the log 
    console.log(response) 
    },function(error){ 
    //if error show the error message in the log 
    console.log('Error: ' + error.statusText); 
    } 
); 

위의 예에서 알 수 있습니다. 첫 번째 콜백 함수는 성공을 처리하고 두 번째 콜백 함수는 오류를 처리합니다. 당신이 그걸로 일할 수 있기를 바랍니다.

편집

이에 코드를 개정 해보십시오 :

var ch_item; 

Payment.postInvoice(dataObj, $rootScope.usertoken).then(function(res){ 
     var payment_details = res.data; 
     User.getUserById(res.data.stylist_uuid, res.data.customer_uuid).then(function (stylist) { 
     ch_item = TC_Service.getChatCredentials(stylistInfo.uid, $rootScope.userId, $rootScope.usertoken, dataObj.request_uuid); 
     openModelAlert("Thank you for your booking!"); 
     $location.path('/success'); 
     }); 
    } 
}, 
function (err) { 
     console.log("Something went wrong with the payment, the response is: "+err.message); 
     openModal("Sorry, please come back later."); 
     $location.path('/failure'); 
    }); 
+0

답장을 보내 주셔서 감사합니다. 알다시피 나는 기본 콜백을 사용했으며 현재 플로우에서는 실패한 섹션에 들어 가지 않습니다. 그것은 'if'절을 입력하고 대답과 함께 돌아올 때까지 이미 '기본'페이지로 리디렉션되고 몇 초 후에 "예약 해 주셔서 감사합니다!"라는 메시지가 표시됩니다. 팝업. 멀티 스레드 방식 인 것처럼 보입니다. 나는 흐름을 제어 할 수 있도록 약속을 사용하고 싶었습니다. 그러나 그것은 나를 위해 작동하지 않습니다 .. –

+0

나는 그 이유는 당신이 500ms의 시간 초과 기능을 가지고 있기 때문이라고 생각합니다. if/else 문. 따라서'$ modalInstance.dismiss ('cancel')에 대한 코드; $ 위치.path ('/ default');는 timeout 함수가 아니기 때문에 계속 실행됩니다. 이 코드를 실행하면 제한 시간이 끝난 다음 if 문을 실행하기 시작합니다. –

+0

timeout 함수를 제거하거나'$ modalInstance.dismiss ('cancel'); $ location.path ('/ default');'timeout 함수의 맨 아래에 있습니다. 희망이 도움이됩니다. –