使用Javascript - 承诺
我试图实现与承诺的服务器调用的行为后重定向。使用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);
});
帮我出球员:)
谢谢您的时间..
五
回来时的承诺您不需要放入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');
});
谢谢你的回复。 正如你可以看到我使用了默认的回调,并在当前流动它不会成为失败的部分。它进入“如果”条款,直到它回来一个答案我已经重定向到“默认”页面,几秒钟后,我得到“谢谢您的预订!”弹出。 看起来它是一个多线程的方法。 我想使用的承诺,这样我可以控制流量。但它不为我工作.. –
我认为正在发生的原因是由于这样的事实,你有500毫秒超时功能,在你的if/else语句。因此你的代码为'$ modalInstance.dismiss('cancel'); $ location。path('/ default');'将继续执行,因为它不在超时函数中。当它执行这段代码时,你的超时可能已经完成,然后它将开始执行你的if语句。 –
要么摆脱超时功能,要么把你的'$ modalInstance.dismiss('取消'); $ location.path('/ default');'在超时函数的底部。希望有所帮助。 –
_“之前,我从服务器得到任何响应的浏览器重定向” _是重定向到'“/默认”'? $ location.path('/ default');'?的目的是什么? – guest271314
你的第二个回调使用了参数'res',但是当前没有收到任何参数。实际上你应该在第二个回调中添加一个名为'err'的参数,并使用它来代替'res'。这些只是争论的名称,所以你可以真正使用任何你想要的。但是,按照惯例,'onRejected()'回调函数应该有一个名为'err'的参数。 – fvgs
你确定之前有任何回应?如果这是问题,那么承诺不起作用,这个代码与它无关。另外,当你使用angular setTimeout将不会被角度同步,你可以尝试使用$超时这个。 –