This article mainly introduces how to deal with batch deferred in jquery. If you need it, you can refer to this code to follow the implementation of $. when () in jquery source code.
The Code is as follows:
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 ");
});
Output result:
The Code is as follows:
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