2016-04-25 77 views
0

我希望我能解決我的問題。JQuery承諾函數已包含回調

我有一個名爲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

看起來像你將不得不在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 
} 
+0

我需要調用回調函數內解決()如果我想與推遲返回一個值嗎? – Jason

+0

是的。所以就像如果你的承諾對象是這樣的'new Promise(function(resolve,reject){call the resolve(「value from call); ....'然後當你做'confirmTraining()。then(confirmNextAvailableTraining (傳遞給resolve()的值在這裏使用))' –