JS Multiple callback function

Source: Internet
Author: User
Tags hasownproperty

Multiple callback issues

The front-end programming, mostly through the interface Exchange data, interface calls are asynchronous, processing data are in the callback function.

If you need to create a file for a user, you need to prepare the following data, and then call the file interface

name //user name using interface get_name (userid)

Files //user attachment using interface Get_atta (userid,name,location)

Create_record (userid,name,location) //Call to build the file interface

Create_files   (Recordid,userid,files) //upload user files

To solve this problem, you can call the name interface first, call the addr interface in its callback, and then call Create_record in the addr callback ....

This is hard to imagine, the code will be written very long, the callback nested multi-layered. Although it solves the problem, it is difficult to sort out the problem with the program code order execution, and if the callback is more, the code will be difficult to maintain. It's dizzy at first sight.

Perhaps synchronization is the entry async is the advanced, the former look, the latter think

Synchronization method

Still use the program order to execute the idea, the code sequence written out, (if the interface is synchronized to get results)

function CreateRecord (userid) {
varget_name (userid);     varGet_atta (userid,name,location);   varCreate_record (userid,name,location); Create_files (Recordid,userid,files);
}

Async methods do not get the correct results, but if you try to make the above code order execution, execute the 1th method and then execute the 2nd ..., that is, the idea of synchronization. Then you can get the right result.

Sequential wait

Wait for the previous method callback, and then execute the following method.

Let user = {Userid:1} //save parameter let IsOk=false; //When all succeeds, set to True
// function CreateRecord() {
   //Get name if(!user.hasownproperty (' name ')) {
//Async method Parameter 1: Data 2: Execute on Success 3: Execute get_name on Failure (user, (res)= {
User.Name=Res. Name;
Console.log (' Get name success ');
//Successfully obtained results, recursive invocation. Because of the if condition, recursion is not repeated CreateRecord (); }, (Err) = { //unsuccessful, method end });
//Ensure that the subsequent method is executed when the asynchronous return succeeds    return; }
//Get File Data if(!user.hasownproperty (' Files ') {Get_atta (user, (res)={user.files=Res. Attas;
Console.log (' Get file Success ') CreateRecord (); }, (Err)= { // }); return; } //file interface, return ID if(!user.hasownproperty (' RecordId ')) { .....return; } //Invoke document interface, upload when file is available if(User.files.length > 0) {create_files (user, (res)= {
The last interface, when successfully returned, indicates that all requests were successful
console.log (' upload file succeeded ') IsOk=true; }, (Err)= { // }); } Else{isOk=true; } }

Each time the recursion is performed, only one of the if blocks is executed, the IF block is the interface call, and when successfully returned, refreshes the if condition, resumes recursion, and fails without recursion.

In this way, "sequential execution" is simulated. In the idea of a clearer, and synchronous method of sequential execution of ideas one to.

This method has many disadvantages, first of all, this method is the mechanically of synchronous interface method in form. Writes the methods of all request interfaces sequentially in a method, using the IF condition to determine whether execution is performed, using recursion repeatedly.

If block code is longer, when more, the whole method is very long and difficult to maintain. The method is intended to "control the sequential execution of each interface method", which is just a container of code.

Conditional logic is complex, if the decision condition is wrong, or forget to refresh the decision condition, it is easy to cause infinite recursion, the program crashes.

Sequential invocation

Write the If block as a stand-alone method in which you call the method of the next step until the last method is called.

Let user = {userid:1}//Save ParametersLet isOk =false;//when all is successful, set to True  //Get the name  functiongetName (user) {get_name (user, (res)={User.Name=Res.      Name; //after success, call get Document Method Getatta(user);  }); }  //Get Documents  function Getatta(user) {Get_atta (user, (res)={user.files=Res.      Attas; //after success, call the file-building method createrecord(user); })  }  //Create a profile  function createrecord(user) {Create_record (user, (res)={User.recordid=Res.      RecordId; //after success, call the upload file method createfiles(user); })  }  //Uploading document Methods  function createfiles(user) {if(User.files.length = = 0) {isOk=true; return; } create_files (User, (res)={isOk=true; })  }  //calledGetName (user);

This approach, compared to recursion, does not write all methods into a single method, but instead splits them into independent methods, and each method calls the next method. Finally, all requests are completed.

No conditional statement logic is clearer, each interface method completes its own task of fetching data, there is a starting method, and the last End method, the chain ring type. In order, one by one. If one of the errors occurs, then terminate.

Each method is independent, still in accordance with the recursive method of invoking the subsequent method, compared to all methods written in the recursive method, only in the form of separation, perhaps good maintenance, but the lack of "encapsulation".

Container method

Combining the characteristics of the first two approaches, the execution of a class management method, the return value, and the error message are created.

    functionMoreajax () { let self= This; //True when all is successfulSelf. Allok =false; //method ContainerLet ajaxlist = []; //return value Container when each method succeedsSelf. Reslist = []; //return value container for each method errorSelf. Errlist = []; //Method Execution SequenceLet index = 0; //Add MethodSelf.add =function(method) {Ajaxlist.push (method); }      //Execute by Add when on/offSelf.start =function ()      {        if(Index = =ajaxlist.length) {//All successful identitiesSelf. Allok =true; return; }        //Ajaxlist[index] ((res)={Console.log (' (Success) execute serial number ' +index); //Save Callback resultsSelf .            Reslist.push (RES); //recursive invocation, execution of the next methodindex = index + 1;          Self.start (); }, (Err)={Console.log (' (Error) Execute serial number ' +index); //Save Error resultsSelf .          Errlist.push (ERR);      }); }    }    //calledLet test =NewMoreajax (); //Add MethodTest.add ((success, error) ={get_name (res)={Success (res)}, (Err)={success (ERR)})}) //Add method againTest.add ((success, error) ={get_location (res)={Success (res)}, (Err)={success (ERR)})}) //Add the Last methodTest.add ((success, error) ={Success ("Lastmethod"); if(send. Allok) {Console.log (send.         Reslist); } Else{console.log (send.         Errlist); }    })    //StartTest.start ();

Container method is the optimization of the first two methods, taking into account the "encapsulation" and flexibility.

The Add method adds an interface method that requires the first two parameters of the 1th to be executed on success, and the 2nd to execute on failure. Adds a method to ajaxlist each time the add is called.

When the Start method executes, the method starts executing in the order of add, and when each method executes, the return value is logged if it succeeds, and the failed record fails. These values are accessed through the Reslist and Errlist array properties.

If each method returns correctly, it executes to the last method in Ajaxlist, and if one fails, it stops.

When each method succeeds, Reslist adds a result. When the first method succeeds, the method after the result value is reslist[0] can access the result returned by the previous method through this property.

JS Multiple callback function

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.