Posted in Javascript onJanuary 22, 2014
此代码仿照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
jquery中对于批量deferred的处理方法
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@