我希望我能解决我的问题。
我有一个本地开发的JS库,名为ConfirmDialog。 ConfirmDialog具有两个回调:onConfirmYes()和onConfirmNo()。这是一个用法示例:
ConfirmDialog.onConfirmYes() = function() {
// make a jQuery ajax call
}
ConfirmDialog.onConfirmNo() = function() {
// make a different ajax call
}
ConfirmationDialog.confirm("Are you sure you wish to do this?");
我需要做的是使用jQuery Deferred / Promise将其链接在一起。
var confirmTraining = false;
var confirmNextAvailDate = false;
function confirmTraining() {
ConfirmDialog.onConfirmYes() = function() {
// make a jQuery ajax call to accept training,
// successful ajax call sets confirmTraining
// to true
}
ConfirmDialog.onConfirmNo() = function() {
// make a different ajax call to decline training,
// successful ajax call sets confirmTraining to
// false
}
ConfirmationDialog.confirm("Do you wish to accept training?");
}
function confirmNextAvailableTraining() {
if (confirmTraining == true) {
ConfirmationDialog.onConfirmYes() = function() {
// ajax call to reserve training, success sets
// sets confirm next date to true
}
ConfirmationDialog.onConfirmNo() = function() {
// ajax call to put person on waitlist
}
ConfirmationDialog.confirm("Do you wish for the next available class?");
}
}
// so on
第二种方法将需要访问由第一种方法进行的ajax调用的结果所设置的布尔值。
所以,这是我需要做的:
// wrong syntax, I know
confirmTraining().then(confirmNextAvailableTraining).finally(function() {
// whatever else needs doing
}
我的问题是,由于直到对ConfirmDialog的回调触发后才设置变量,所以我无法弄清楚如何为希望链接的方法设置Deferred / Promise。
有人可以帮忙吗?
杰森
最佳答案
看起来您将不得不在confirmDialog.onConfirmYes()
和confirmDialog.onConfirmNo()
中实际使用Promise对象。
ConfirmDialog.onConfirmYes = function() {
//create a promise object that will make the call
// return the promise object
}
ConfirmDialog.onConfirmNo = function() {
//create a promise object that will make the call
// return the promise object
}
function confirmTraining() {
var aPromiseobj;
if(logic to determine what was picked)
aPromiseobj = ConfirmDialog.onConfirmYes();
}else{
aPromiseobj = ConfirmDialog.onConfirmNo()
}
return aPromiseobj;
}
现在,当您调用
then
时,它将位于一个promise对象上confirmTraining().then(confirmNextAvailableTraining).finally(function() {
// whatever else needs doing
}