Home > WeChat Applet > Mini Program Development > The implementation process of asynchronous process processing by Promise in WeChat applet

The implementation process of asynchronous process processing by Promise in WeChat applet

黄舟
Release: 2018-05-15 17:10:08
Original
2024 people have browsed it

This article mainly introduces relevant information on the detailed examples of using Promise for asynchronous process processing in WeChat mini programs. Here is a detailed explanation of how to use Promise to process asynchronous processes and provides specific implementation steps. Friends in need can refer to it. Next

Detailed explanation of examples of using Promise for asynchronous process processing in WeChat mini programs

We know that JavaScript is executed in a single process, and synchronous operations will affect the execution of the program. Blocking processing. For example, in a browser page program, if a piece of synchronized code takes a long time to execute (such as a large loop operation), the page will become stuck.

So, in JavaScript, some asynchronous features are provided to provide performance and experience benefits for the program. For example, the code can be executed in setTimeout(); or in web pages, we use Ajax Method to make asynchronous data request to the server. These asynchronous codes will not block the current interface main process, and the interface can still operate flexibly. The corresponding processing will be done after the asynchronous code execution is completed.

A typical piece of asynchronous code looks like this:

function asyncFunc(callback) {
 setTimeout(function () {
  //在这里写你的逻辑代码
  //...

  //逻辑代码结束,执行一个回调函数
  callback();
 }, 5000);
}
Copy after login

Or:

function getAccountInfo(callback, errorCallback) {
 wx.request({
  url: '/accounts/12345',
  success: function (res) {
   //...
   callback(data);
  },
  fail: function (res) {
   //...
   errorCallback(data);
  }
 });
}
Copy after login

Then we call it like this:

asyncFunc(function () {
 console.log("asyncFunc() run complete");
});

getAccountInfo(function (data) {
 console.log("get account info successfully:", data);
}, function () {
 console.error("get account info failed");
});
Copy after login

This is a callback function to control the way code execution flows. This seems fine and easy to understand.

However, if we have too many asynchronous operations in a piece of code, and we need to ensure that these asynchronous operations are executed in order, then our code will look very bad, like this:

asyncFunc1(function(){
 //...
 asyncFunc2(function(){
  //...
  asyncFunc3(function(){
   //...
   asyncFunc4(function(){
    //...
    asyncFunc5(function(){
      //...
    });   });
  });
 });
});
Copy after login

The readability and maintainability of such code can be imagined. Also, the real problem with callback functions is this:

It takes away our ability to use the return and throw keywords.

So is there any way to improve this problem? The answer is yes, the emergence of the concept of Promise solves all this well. Regarding what Promise is, there are a lot of introductions after searching. I will not copy and paste here. I will mainly talk about how we use it to solve our problems.

Let’s take a look at what the above example would look like if we used Promise? Let’s first change these functions into Promise:

function asyncFunc1(){
 return new Promise(function (resolve, reject) {
  //...
 })
}

 
// asyncFunc2,3,4,5也实现成跟asyncFunc1一样的方式...
Copy after login

Then look at how they are used Called:

asyncFunc1()
 .then(asyncFunc2)
 .then(asyncFunc3)
 .then(asyncFunc4)
 .then(asyncFunc5);
Copy after login

In this way, these asynchronous functions will be executed one by one in order.

ES6 natively supports Promise, but in environments where Promise is not natively supported, we have many third-party libraries to support it, such as Q.js and Bluebird. In addition to providing standard Promise APIs, they generally also provide some non-standard but very useful APIs, making the control of asynchronous processes more elegant.

We can see from the API documentation of the WeChat applet that many functions in the JavaScript API provided by the framework are actually asynchronous, such as wx.setStorage(), wx.getStorage(), wx.getLocation( ), etc., they are also the callback processing methods provided. By passing in the success, fail, and complete callback functions in the parameters, the success or failure of the operation can be processed separately.

For example:

wx.getLocation({ 
 type: 'wgs84', 
 success: function(res) { 
  var latitude = res.latitude 
  var longitude = res.longitude 
  var speed = res.speed 
  var accuracy = res.accuracy 
 },
 fail: function() {
  console.error("get location failed")
 }
})
Copy after login

Can we make the asynchronous API of WeChat applet support Promise? The answer is yes, of course we can use Promise to wrap these APIs one by one, but this is still quite troublesome. However, since the parameter format of the API of the mini program is relatively uniform, it only accepts one object parameter, and the callbacks are all set in this parameter. Therefore, this provides convenience for our unified processing, and we can write a non-intrusive tool. Method to complete such work:

Suppose we write this tool method into a file named util.js:

var Promise = require('../libs/bluebird.min')  //我用了bluebird.js
function wxPromisify(fn) { 
 return function (obj = {}) {  
  return new Promise((resolve, reject) => {   
   obj.success = function (res) {    
    resolve(res)   
   }   

   obj.fail = function (res) {    
    reject(res)   
   }   

   fn(obj)  
  }) 
 }
}

module.exports = { 
 wxPromisify: wxPromisify
}
Copy after login

After that, let’s take a look at how to use this method , changing the original callback API to the Promise method:

var util = require('../utils/util')

var getLocationPromisified = util.wxPromisify(wx.getLocation)

getLocationPromisified({
 type: 'wgs84'
}).then(function (res) {
 var latitude = res.latitude 
 var longitude = res.longitude 
 var speed = res.speed 
 var accuracy = res.accuracy 
}).catch(function () {
 console.error("get location failed")
})
Copy after login

Is it easy to understand?

The above is the detailed content of The implementation process of asynchronous process processing by Promise in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template