這篇文章主要介紹了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