2016-07-04 128 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); 
}); 

幫我出球員:)

謝謝您的時間..

+0

_「之前,我從服務器得到任何響應的瀏覽器重定向」 _是重定向到'「/默認」'? $ location.path('/ default');'?的目的是什麼? – guest271314

+0

你的第二個回調使用了參數'res',但是當前沒有收到任何參數。實際上你應該在第二個回調中添加一個名爲'err'的參數,並使用它來代替'res'。這些只是爭論的名稱,所以你可以真正使用任何你想要的。但是,按照慣例,'onRejected()'回調函數應該有一個名爲'err'的參數。 – fvgs

+0

你確定之前有任何迴應?如果這是問題,那麼承諾不起作用,這個代碼與它無關。另外,當你使用angular setTimeout將不會被角度同步,你可以嘗試使用$超時這個。 –

回答

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

謝謝你的回覆。 正如你可以看到我使用了默認的回調,並在當前流動它不會成爲失敗的部分。它進入「如果」條款,直到它回來一個答案我已經重定向到「默認」頁面,幾秒鐘後,我得到「謝謝您的預訂!」彈出。 看起來它是一個多線程的方法。 我想使用的承諾,這樣我可以控制流量。但它不爲我工作.. –

+0

我認爲正在發生的原因是由於這樣的事實,你有500毫秒超時功能,在你的if/else語句。因此你的代碼爲'$ modalInstance.dismiss('cancel'); $ location。path('/ default');'將繼續執行,因爲它不在超時函數中。當它執行這段代碼時,你的超時可能已經完成,然後它將開始執行你的if語句。 –

+0

要麼擺脫超時功能,要麼把你的'$ modalInstance.dismiss('取消'); $ location.path('/ default');'在超時函數的底部。希望有所幫助。 –