Explanation of asynchronous processing of small programs and asynchronous explanation of small programs
The examples in this article share with you the specific asynchronous Processing Methods of small programs for your reference. The specific content is as follows:
Check the problem directly:
Then read the printed result:
The above two figures show that the network request is executed first in the code and then the printed variable is executed. However, according to the output below, the first output result is the function that executes the printing variable (aafn function), and then prints the data returned from the callback of the network request success and the value of the assigned variable;
Why the aafn is executed first, and the printed value is not assigned a value?
Since wx. request is an asynchronous request, you can continue to execute the function down while requesting data. Therefore, the variable value is printed before the value is assigned;
How can this problem be solved?
Method 1:
Nesting
Execute the aafn function in the success callback of wx. request.
Then run the result
Here we get the value.
However, if the logic is complex, multiple layers of Asynchronization are required, like this:
asyncFn1(function(){ //... asyncFn2(function(){ //... asyncFn3(function(){ //... asyncFn4(function(){ //... asyncFn5(function(){ //... }); }); }); });});
In this way, the code looks pretty bad, and the code's readability and maintainability are not good.
How can this problem be solved? The concept of Promise solves all this well. What is Promise? I will not talk about it here. If you are interested, go and have a look. Promise introduction link.
Let's take a look at the Promise method:
Function asyncFn1 () {return new Promise (function (resolve, reject ){//...})} // asyncFn2, 3,4, and 5 are also implemented in the same way as asyncFn1...
Call
asyncFn1() .then(asyncFn2) .then(asyncFn3) .then(asyncFn4) .then(asyncFn5);
In this way, the asynchronous function can be executed in sequence.
How does the asynchronous API of A applet support Promise? We can use Promise to package these Apis one by one, but this is still troublesome. However, the parameter formats of the mini-program API are uniform, and only one object parameter is accepted. The callback is set in this parameter. Therefore, this facilitates unified processing, write a tool method to complete this job
First, you must reference a file named bluebird. js;
Go to the official bluebird website to download:
This does not seem to be downloadable, but you can click to enter, copy it, create a js file in the applet, copy the code to this js file, and then reference it.
Then write another JS file, and write the tool method:
Below is the prom. js
Then introduce the prom. js in the js of the page to be used:
Call:
Print results
In this way, you can complete the process.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.