Jason
Jason

Reputation: 4130

JQuery Promises On Functions Already Containing Callbacks

I'm hoping I can get my problem across.

I have a locally developed JS library called ConfirmDialog. ConfirmDialog has two callbacks: onConfirmYes() and onConfirmNo(). Here's a usage example:

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?");

What I need to do is chain this together using 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

The second method will require access to the boolean value set by the result of an ajax call made by the first method.

So, here's what I need to do:

// wrong syntax, I know
confirmTraining().then(confirmNextAvailableTraining).finally(function() {
    // whatever else needs doing
}

The problem I have is that since the variables are not set until the callback fires for the ConfirmDialog, I cannot figure out how to set up the Deferred/Promise for the methods I wish to chain.

Can anyone help?

Jason

Upvotes: 0

Views: 58

Answers (1)

Jack Thor
Jack Thor

Reputation: 1594

Look like you will have to actually use a promise object inconfirmDialog.onConfirmYes() and 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;
}

Now when you called then it will be on a promise object

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

Upvotes: 1

Related Questions