У меня есть следующие четыре функции, в которых вызовы two(), three() и four() будут вызываться, когда с параметром появляется разрешение обещания. Позвольте мне объяснить, немного дальше.Как выполнить модульное тестирование jQuery Promises?
Когда я вызываю функцию one(), я передаю значение параметра по умолчанию, но функция function() будет вызываться с разрешенным значением обещания в функции one(). Аналогичная логика следует для функций two(), three() и four().
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);
У вас есть отложенные антипаттерны там, $ .ajax уже возвращает обещание - использовать его. –
Кроме того, я могу понять ваш код просто отлично, но я понятия не имею, что вы спрашиваете здесь. –
@BenjaminGruenbaum Я хотел бы написать единичные тестовые примеры вышеуказанного кода, чтобы позже я мог применять подобные идеи –