我有以下四個函數,其中兩個(),三個()和四個()將在promise參數發生時被調用。讓我進一步解釋一下。當我調用函數one()時,我傳遞了默認參數值,但函數two()將在函數one()中用解析的promise值調用。函數two(),three()和four()的類似邏輯如下。如何做單元測試jQuery的承諾?
function one(arg) {
var deferred = $.Deferred(); // Don't worry yet what this is until after you understand the flow
console.log("Starting one's ajax with arg: " + arg);
$.ajax({
url: '/',
success: function() {
// Here's where you want to call the next function in the
// list if there is one. To do it, call deferred.resolve()
console.log('Finished with one. Ready to call next.');
deferred.resolve("This is one's result");
}
});
// The deferred object has a "promise" member, which has a "then" function
return deferred.promise();
}
function two(arg) {
var deferred = $.Deferred();
console.log("Starting two's ajax with arg: " + arg);
$.ajax({
url: '/',
success: function() {
// Again, this is where you want to call the next function
// in the list if there is one.
console.log('Finished with two. Ready to call next.');
deferred.resolve("This is two's result");
}
});
// The deferred object has a "promise" member, which has a "then" function
return deferred.promise();
}
function three(arg) {
var deferred = $.Deferred();
console.log("Starting three's ajax with arg: " + arg);
$.ajax({
url: '/',
success: function() {
// Again, this is where you want to call the next function
// in the list if there is one.
console.log('Finished with three. Ready to call next if there is one.');
deferred.resolve("This is three's result");
}
});
// The deferred object has a "promise" member, which has a "then" function
return deferred.promise();
}
function four(arg) {
console.log("Starting four with arg: " + arg);
console.log("Finished synchronous four");
}
// Test it out. Call the first. Pass the functions (without calling them, so no parentheses)
// into the "then" calls.
one("arg given to one")
.then(two)
.then(three)
.then(four);
你必須有一個延遲的反模式,$就已經返回了一個承諾 - 使用它。 – 2014-09-02 15:10:09
另外,我可以理解你的代碼,但我不知道你在問這裏。 – 2014-09-02 15:10:37
@BenjaminGruenbaum我想寫上述代碼的單元測試用例,以便稍後我可以應用類似的想法 – 2014-09-02 15:15:43