我看到c不依赖于b结果,并且b不依赖于结果。
遵循 GRASP 原则(http://en.wikipedia.org/wiki/GRASP_(object-oriented_design),a不能知道b , b不能知道c。
当我们编程时,记住 GRASP 的原则或指南是非常重要的。
高内聚和低耦合意味着我们的代码会更好、更可重用和更容易维护。
知道a、b和c的 main 函数必须构建链式调用。
功能将是:
function a(param1, param2) {
var deferred = $.Deferred();
console.log(" function a: begin. Params " + param1 + " and " + param2);
mockPost("a_url").done(function() {
console.log(" function a: end ok. Params " + param1 + " and " + param2);
deferred.resolve();
}).fail(function() {
console.log(" function a: end fail. Params " + param1 + " and " + param2);
deferred.reject();
});
return deferred.promise();
}
function b() {
var deferred = $.Deferred();
console.log(" function b: begin");
mockPost("b_url").done(function() {
console.log(" function b: end ok.");
deferred.resolve();
}).fail(function() {
console.log(" function b: end fail.");
deferred.reject();
});
return deferred.promise();
}
function c() {
// We suppose that c function calls to post function and anything more
return mockPost("c_url");
}
主要功能是:
// Array with params for a function (a function is the first link in chain)
var data = [{param1 : 1235, param2: 3214}, {param1 : 5432, param2: 9876}];
// Array with calls to each fixed sequence a, b, and c. We iterate over data array
var arrayFunctions = [];
$.each(data, function(i,obj) {
arrayFunctions.push(
function() {
console.log("Params in data with index " + i + ":");
// We define the fixed sequence: a with params, b without params and c without params
return $.iterativeWhen(
function() {
return a(obj.param1, obj.param2);
},
b,
c
);
}
)
});
// Start the global process
$.iterativeWhen.apply($, arrayFunctions)
.done(function() {
console.log ("----------------");
console.log ("> Global Success");
})
.fail(function() {
console.log ("--------------");
console.log ("> Global Fail");
});
$.iterativeWhen 在 jQuery 中不存在,所以我构建了它。它适用于 jQuery 1.8 和更高版本。
$.iterativeWhen = function () {
var deferred = $.Deferred();
var promise = deferred.promise();
$.each(arguments, function(i, obj) {
promise = promise.then(function() {
return obj();
});
});
deferred.resolve();
return promise;
};
mockPost 函数以成功概率模拟对 $.post 的调用:
function mockPost(url) {
var deferred = $.Deferred();
setTimeout(function() {
if (Math.random() <= 0.9) {
console.log(" request url: " + url + "... ok");
deferred.resolve();
} else {
console.log(" request url: " + url + "... fail");
deferred.reject();
}
}, 1000);
return deferred.promise();
}
日志输出为:
Params in data with index 0:
function a: begin. Params 1235 and 3214
request url: a_url... ok
function a: end ok. Params 1235 and 3214
function b: begin
request url: b_url... ok
function b: end ok.
request url: c_url... ok
Params in data with index 1:
function a: begin. Params 5432 and 9876
request url: a_url... ok
function a: end ok. Params 5432 and 9876
function b: begin
request url: b_url... ok
function b: end ok.
request url: c_url... ok
----------------
> Global Success
jsFiddle在这里:http: //jsfiddle.net/E2tp3/