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

May 15, 2018 pm 05:10 PM
promise Applets process

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open multiple Toutiao accounts? What is the process for applying for a Toutiao account? How to open multiple Toutiao accounts? What is the process for applying for a Toutiao account? Mar 22, 2024 am 11:00 AM

With the popularity of mobile Internet, Toutiao has become one of the most popular news information platforms in my country. Many users hope to have multiple accounts on the Toutiao platform to meet different needs. So, how to open multiple Toutiao accounts? This article will introduce in detail the method and application process of opening multiple Toutiao accounts. 1. How to open multiple Toutiao accounts? The method of opening multiple Toutiao accounts is as follows: On the Toutiao platform, users can register accounts through different mobile phone numbers. Each mobile phone number can only register one Toutiao account, which means that users can use multiple mobile phone numbers to register multiple accounts. 2. Email registration: Use different email addresses to register a Toutiao account. Similar to mobile phone number registration, each email address can also register a Toutiao account. 3. Log in with third-party account

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Are Douyin sleep anchors profitable? What are the specific procedures for sleep live streaming? Are Douyin sleep anchors profitable? What are the specific procedures for sleep live streaming? Mar 21, 2024 pm 04:41 PM

In today's fast-paced society, sleep quality problems are plaguing more and more people. In order to improve users' sleep quality, a group of special sleep anchors appeared on the Douyin platform. They interact with users through live broadcasts, share sleep tips, and provide relaxing music and sounds to help viewers fall asleep peacefully. So, are these sleep anchors profitable? This article will focus on this issue. 1. Are Douyin sleep anchors profitable? Douyin sleep anchors can indeed earn certain profits. First, they can receive gifts and transfers through the tipping function in the live broadcast room, and these benefits depend on their number of fans and audience satisfaction. Secondly, the Douyin platform will give the anchor a certain share based on the number of views, likes, shares and other data of the live broadcast. Some sleep anchors will also

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How to operate mini program registration How to operate mini program registration Sep 13, 2023 pm 04:36 PM

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles