我試圖實現與承諾的服務器調用的行爲後重定向。使用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);
});
幫我出球員:)
謝謝您的時間..
五
_「之前,我從服務器得到任何響應的瀏覽器重定向」 _是重定向到'「/默認」'? $ location.path('/ default');'?的目的是什麼? – guest271314
你的第二個回調使用了參數'res',但是當前沒有收到任何參數。實際上你應該在第二個回調中添加一個名爲'err'的參數,並使用它來代替'res'。這些只是爭論的名稱,所以你可以真正使用任何你想要的。但是,按照慣例,'onRejected()'回調函數應該有一個名爲'err'的參數。 – fvgs
你確定之前有任何迴應?如果這是問題,那麼承諾不起作用,這個代碼與它無關。另外,當你使用angular setTimeout將不會被角度同步,你可以嘗試使用$超時這個。 –