How to deal with batch deferred in jquery _ jquery-js tutorial

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.