Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use JavaScript Asynchronous programming

Shulou Source: shulou.com Published: 2022-05-31 11:52:49 10月15日 Update

This article mainly explains "how to use JavaScript asynchronous programming". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use JavaScript asynchronous programming.

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

For example, the following code:

$.get ($C.apipathic charge. find id:memberId, {id:memberId}, function (data) {if (data.error) {layer.close (memberLayer); padInOut (padId,memberId); allPads ();}})

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

My final solution is the callback function: add the callback function to the definition of the padInOut function, 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 executed and the callback function exists, the callback function is executed. At this point, when the function is executed, you can achieve the goal by passing parameters:

PadInOut (padId,memberId,allPads)

Callback functions are commonly used in js asynchronous programming. However, there is a downside to using the callback function, that is, it will cause callback hell.

Thank you for your reading, the above is the content of "how to use JavaScript asynchronous programming". After the study of this article, I believe you have a deeper understanding of how to use JavaScript asynchronous programming, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Functions programming statements code methods results learning content order success it doesn't matter three bad function at the same time place hell that is regular meetings ideas Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Docker Shulou Technology Linux