On asynchronous programming of JavaScript

  • 2021-07-12 05:10:21
  • OfStack

When I first learned js a year ago, I saw many explanations about asynchronous programming. However, due to the lack of practical experience, there is no way to understand too much, and things that are too theoretical are often forgotten after reading.

After the company's 3 two project training, js asynchronous programming has a more specific understanding. However, it is always shallow to get started, so it should be a staged summary for yourself here.

In asynchronous programming, the execution of a statement cannot depend on the result of the completion of the previous statement, because it is impossible to predict when a statement will be completed, which has nothing to do with the code order, and the statements are executed concurrently.

For example, the following code:


$.get($C.apiPath+'ucenter/padCharge/findMember' , {id:memberId},function(data){
  if(data.error){
    layer.close(memberLayer);
    padInOut(padId,memberId);
    allPads();
  }
});

The role of these three sentences in the context is to close a bomb layer (1), execute padInOut function (2) and allPads function (3) after completing an ajax access and successfully obtaining data; It doesn't matter the order of (1), but I want (3) to be executed after (2). However, these words of code can't achieve the desired result, because three functions are executed at the same time, and allPads can't wait for padInOut to execute, so the result will certainly go wrong.

My final solution is callback function: add callback function to padInOut function definition, as follows:


function padInOut(padId,memberId,callback){
     $F.POSTLoading($C.apiPath + 'ucenter/padCharge/padInOut',{id:padId,memberId:memberId},function(data){
         if(callback)callback()
     });
 }; 

When the method is finished and the callback function exists, the callback function is executed. At this time, when the function is executed, the purpose can be achieved by passing parameters:

padInOut(padId,memberId,allPads)

Callback function is a common method used in js asynchronous programming. However, there is a disadvantage to using callback function, that is, it will cause callback hell. Therefore, the new es standard is constantly seeking solutions to callback. This is another story, and this article is written here.


Related articles: