所以我对这些承诺很新。我很难缠绕他们。我已经查看了大量的帖子和SO帖子,但是没有发现像我的情况。 这是我目前的代码。
$("#PayNow, input[name^='schedulepmt']").on("blur", function(){
var diff = 0;
diff = calcBalanceDue();
if(diff){
$.when(confirmNewPayment(diff)).then(function(){
if($(this).attr("id") === "PayNow" && input[name^='schedulepmt'].length && ($(this).val() !== $(this).data("prevValue"))){
if(!resetPmtInfo()) {
$(this).val($(this).data("prevValue"));
}
}
});
}
});
我希望.then()
内的代码在执行confirmNewPayment()
后执行。它似乎仍然都是异步运行。
感谢。
以下是confirmNewPayment()
function confirmNewPayment(diff){
bootbox.dialog({
message: "There is an outstanding balance. How would you like to proceed?",
title: "Outstanding Balance Options",
closeButton: false,
buttons: {
addpmt: {
label: "Add a scheduled CC payment",
className: "btn-success",
callback: function() {
scheduledPmtData.PaymentCount += 1;
$("#ScheduledPayments").append($("#ScheduledPmtTemplate").render(scheduledPmtData,{amount:diff}));
}
},
collect: {
label: "Mark balance as \"To Collect\"",
className: "btn-primary",
callback: function() {
$("#BalanceDueRow").removeClass("hide");
$("#BalanceDue").val(diff);
}
}
}
});
}
答案 0 :(得分:2)
您的confirmNewPayment函数应该返回一个承诺:
function confirmNewPayment(diff){
var deferred = $.Deferred();
// Your async action here
(function() {
// $when will run your function when the deferred object is resolved
deferred.resolve(diff * 2);
})();
return deferred.promise();
}
更新:
如果bootbox通过设计返回承诺,那么一切都会更容易。所以在这种情况下你可以做到
function confirmNewPayment(diff){
var deferred = $.Deferred();
bootbox.dialog({
message: "There is an outstanding balance. How would you like to proceed?",
title: "Outstanding Balance Options",
closeButton: false,
buttons: {
addpmt: {
label: "Add a scheduled CC payment",
className: "btn-success",
callback: function() {
scheduledPmtData.PaymentCount += 1;
$("#ScheduledPayments").append($("#ScheduledPmtTemplate").render(scheduledPmtData,{amount:diff}));
deferred.resolve('schedule');
}
},
collect: {
label: "Mark balance as \"To Collect\"",
className: "btn-primary",
callback: function() {
$("#BalanceDueRow").removeClass("hide");
$("#BalanceDue").val(diff);
deferred.resolve('mark');
}
}
}
});
return deferred.promise();
}
...
$("#PayNow, input[name^='schedulepmt']").on("blur", function(){
....
confirmNewPayment(diff).then(function(selection) {
// selection is 'schedule' or 'mark'
});
}