【发布时间】:2014-09-02 14:53:53
【问题描述】:
我有以下四个函数,当使用参数进行承诺解析时,将调用 two()、three() 和four()。让我再解释一下。
当我调用函数 one() 时,我传递了默认参数值,但是函数 two() 将使用函数 one() 中的 promise 的解析值调用。函数 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 我想编写上述代码的单元测试用例,以便以后可以应用类似的想法
标签: jquery ajax unit-testing promise