jquery中对于批量deferred的处理方法
人气:0此代码仿照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
加载全部内容