jquery中对于批量deferred的处理方法
此代码仿照jquery中$.when()的实现
. 代码如下:
function test(i) {
var dfd = $.deferred();
if(i%2 == 0) {
console.log("resolve " + i);
dfd.resolve();
} else {
console.log("failure " + i);
dfd.reject();
}
return dfd.promise();
}
function call() {
var dfd = $.deferred();
var remain = 10;
for(var i=0;i< 10;i++){
test(i).done(function() {
if(!(--remain)) {
dfd.resolve();
}
}).fail(function() {
if(!(--remain)) {
dfd.resolve();
}
})
}
return dfd.promise();
}
call().done(function() {
console.log("all finished");
});
输出结果:
. 代码如下:
resolve 0 test.js:4
failure 1 test.js:7
resolve 2 test.js:4
failure 3 test.js:7
resolve 4 test.js:4
failure 5 test.js:7
resolve 6 test.js:4
failure 7 test.js:7
resolve 8 test.js:4
failure 9 test.js:7
all finished