SoFunction
Updated on 2025-03-03

Summary of mini program on request synchronization

In JavaScript, some asynchronous features are provided because synchronous operations block the execution of the program. For example, in a browser page program, if a synchronized piece of code needs to be executed for a long time (such as a large loop operation), the page will become stuck.

Asynchronous provides performance and experience benefits for the program, such as putting the code into setTimeout() to execute; or on web pages, we use Ajax to make asynchronous data requests to the server side. These asynchronous codes will not block the current main interface process. The interface can still operate flexibly. After the asynchronous code is executed, the corresponding processing will be done.

For example: In a mini program, the usage time of data we obtain from the background is often uncertain. At this time: even the code you wrote in the previous section may be executed later.

function getAccountInfo(callback, errorCallback) {
 ({
 url: '/accounts/12345',
 success: function (res) {
  console("1") },
 fail: function (res) {
  //...
  errorCallback(data);
 }
 });
("2")
}

That is, there is a possibility that 2 output is before 1. This strategy improves page loading speed. It can greatly improve the user experience.

But please see the following scenario:

Mini programs advocate using it without obtaining user information, but in specific circumstances we must obtain some user data, such as name, image link, etc. In this case, we first get the user's code and go to the background to get the user's openid or unionid according to the code. Only after obtaining this data can we determine the user's identity and then send a new request (these requests often require user identity credentials, such as tokens).

In the above statement, we made three requests, the first time we got the code, the second time we got the openID or unionid, and the third time we performed a new request based on the identity information. We all know that requests in JS are executed asynchronously. It is possible that the code on the WeChat server has not returned yet, and the user has already performed some operations that require permissions, which will cause the request to fail. So how can mini programs solve this problem? Here are three solutions for reference:

1. All requests are processed on the server side at one time. (The range of use is too small)

2. The client sends the request again in the callback with the successful request. (Available, but the code will be lengthy and not easy to maintain)

3. Use Promise

Solution 1: For example, the user message function, after we get the code and message content, we send it to the server, the server opens a new thread to process these business logic, and the main thread directly returns the prompt that the user message is successful (the situation of failure of the execution of the new thread is not considered here).

Solution 2 and Solution 3 are the same in functions, but the code display may be better. Look at the following code (where postReq and getReq are the request methods encapsulated by themselves):

var http = require('')
function userLogin(name, image, gender, content, artilceId){
 //Get code var promise = new Promise(function(resolve,reject){
 ({
  success: res => {
  resolve();
  }
 })
 })
 //Get user identity credentials var pm2 = (function(res){
 return new Promise(function (resolve, reject){
  ("user/getUserInfo", { "code": res, "type": 1, "name": name, "image": image, "gender": gender }, function (res) {
  // (res)
  if ( == "") {
   ({
   title: 'hint',
   content: 'Authorization failed, please try again',
   })
   return;
  }
  resolve(res);
  })
 })
 },function(res){
 
 })
 //Leave a comment (function(res){
 // (+":"+content)
 ("user/comment", { "content": content, "openId": , "artilceId": artilceId},function(res){
  // (res)
  if( ){
  ({
   key: 'showInfo',
   success: function(res) {
   ( )
   if( != false){
    ({
    title: 'hint',
    content: 'In order to maintain the learning atmosphere of learning Java every day, we have sent an email to remind the administrator to review the comments, and you can display your comments after they are approved.  ',
    })
   }
   },fail:function(res){
   ({
    key: 'showInfo',
    data: false,
   })
   ({
    title: 'hint',
    content: 'In order to maintain the learning atmosphere of learning Java every day, we have sent an email to remind the administrator to review the comments, and you can display your comments after they are approved.  ',
   })
   }
  })
 
  }
 
  })
 },
 function(res){
  })
}
 
 = {
 userLogin: userLogin
}

Is Promise used here? We will talk about how to use Promise later, we may ensure synchronization in the beginning stages like this:

 ("/homework/getHomeWorkLike",{"name":name},function(res){
  ("/homework/getHomeWorkLike",{"name":name},function(res){
   ("/homework/getHomeWorkLike",{"name":name},function(res){
 
      }
     })
    }
   })
  }
 })

A new request is executed in each callback that returns a successful return, but when we process too much business logic, it will appear ugly. Because it is not intuitive, it is not convenient for us to check some errors. So it is recommended that you use Promise.

Promise :

Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events. It was first proposed and implemented by the community. ES6 wrote it into the language standard, unified usage, and provided Promise objects natively.

The so-called Promise is simply a container that stores the result of an event that will end in the future (usually an asynchronous operation). Syntactically, a Promise is an object from which messages can be obtained from asynchronous operations. Promise provides a unified API, and various asynchronous operations can be processed in the same way.

Promise objects have the following two characteristics.

(1) The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation with three states: pending (in progress), fulfilled (successfully), and rejected (failed). Only the result of asynchronous operation can determine which state it is currently in, and no other operation can change this state. This is also the origin of the name Promise. Its English means "promise", which means that other means cannot be changed.

(2) Once the state changes, it will not change again, and you can get this result at any time. There are only two possible ways to change the state of the Promise object: from pending to fulfilled and from pending to rejected. As long as these two situations occur, the state will solidify and will not change again. This result will be maintained. This is called resolved (definitely). If the change has already happened, you will get this result immediately if you add a callback function to the Promise object. This is completely different from an event. The characteristic of an event is that if you miss it and listen to it, you will not get any results.

Note that for the sake of writing convenience, the resolved later in this chapter refers to the fulfilled state only and does not include the rejected state.

With the Promise object, asynchronous operations can be expressed in the process of synchronous operations, avoiding nested callback functions at layers. In addition, the Promise object provides a unified interface, making it easier to control asynchronous operations.

Promise also has some disadvantages. First, the Promise cannot be cancelled. Once it is newly created, it will be executed immediately and cannot be cancelled halfway. Secondly, if the callback function is not set, the error thrown by Promise will not be reflected outside. Third, when in the pending state, it is impossible to know which stage it is currently progressing (it is just beginning or about to be completed).

If certain events keep happening repeatedly, generally speaking, using Stream mode is a better option than deploying a Promise.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.