JQuery承诺已经包含回调函数

时间:2016-04-25 16:32:04

标签: javascript jquery ajax

我希望我可以解决我的问题。

我有一个名为ConfirmDialog的本地开发的JS库。 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之前没有设置变量,我无法弄清楚如何设置我希望链接的方法的延迟/承诺。

有人可以帮忙吗?

杰森

1 个答案:

答案 0 :(得分:1)

看起来您必须在confirmDialog.onConfirmYes()confirmDialog.onConfirmNo()中实际使用承诺对象。

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时,它将在一个承诺对象上

confirmTraining().then(confirmNextAvailableTraining).finally(function() {
 // whatever else needs doing
}