Javascript -在承诺后重定向

Javascript - Redirect after promise

本文关键字:重定向 承诺 Javascript      更新时间:2023-09-26

我正在尝试实现带有承诺的服务器调用行为。

我想要发生的是,当来自服务器的回复是"成功"时,我想重定向到"成功"页面,否则如果是"失败",我想重定向到"失败"页面。

当前的情况是没有等待响应,并且在我从服务器获得任何响应之前,浏览器被重定向到,无论它是成功还是失败。

我做错了什么,我该如何解决?

下面是我代码的相关部分:

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 .

当返回承诺时,您不需要放入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');
    });