Home WeChat Applet Mini Program Development WeChat applet Promise simplified callback example sharing

WeChat applet Promise simplified callback example sharing

May 15, 2018 pm 05:09 PM
promise share Applets

Promise is a solution to asynchronous programming that 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 its usage, and provided Promise objects natively. This article mainly introduces to you how to use Promise to simplify callbacks in WeChat applet. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

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

Understand what a Promise object is

In a project, various asynchronous operations will appear. If there are asynchronous operations in the callback of an asynchronous operation, a callback pyramid will appear.

For example, the following

// 模拟获取code,然后将code传给后台,成功后获取userinfo,再将userinfo传给后台
// 登录
wx.login({
  success: res => {
    let code = res.code
    // 请求
    imitationPost({
      url: '/test/loginWithCode',
      data: {
        code
      },
      success: data => {
        // 获取userInfo
        wx.getUserInfo({
          success: res => {
            let userInfo = res.userInfo
            // 请求
            imitationPost({
              url: '/test/saveUserInfo',
              data: {
                userInfo
              },
              success: data => {
                console.log(data)
              },
              fail: res => {
                console.log(res)
              }
            })
          },
          fail: res => {
            console.log(res)
          }
        })
      },
      fail: res => {
        console.log(res)
      }
    })
  },
  fail: res => {
    console.log(res)
  }
})
Copy after login

Let’s analyze how to use Promise to simplify the code

Because the WeChat applet asynchronous api They are all in the form of success and failure. Someone has encapsulated such a method:

promisify.js

module.exports = (api) => {
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
    });
  }
}
Copy after login

Let’s look at the simplest one first:

// 获取系统信息
wx.getSystemInfo({
  success: res => {
    // success
    console.log(res)
  },
  fail: res => {

  }
})
Copy after login

Use the above promisify. After js is simplified:

const promisify = require('./promisify')
const getSystemInfo = promisify(wx.getSystemInfo)

getSystemInfo().then(res=>{
  // success
  console.log(res)
}).catch(res=>{

})
Copy after login

getSystemInfo

You can see that there is one less indentation in the simplified callback, and the callback function starts from line 9 Reduced to 6 lines.

The simplified effect of the callback pyramid

Then let’s take a look at the initial callback pyramid

const promisify = require('./promisify')
const login = promisify(wx.login)
const getSystemInfo = promisify(wx.getSystemInfo)

// 登录
login().then(res => {
  let code = res.code
  // 请求
  pImitationPost({
    url: '/test/loginWithCode',
    data: {
      code
    },
  }).then(data => {
    // 获取userInfo
    getUserInfo().then(res => {
      let userInfo = res.userInfo
      // 请求
      pImitationPost({
        url: '/test/saveUserInfo',
        data: {
          userInfo
        },
      }).then(data => {
        console.log(data)
      }).catch(res => {
        console.log(res)
      })
    }).catch(res => {
      console.log(res)
    })
  }).catch(res => {
    console.log(res)
  })
}).catch(res => {
  console.log(res)
})
Copy after login

Simplification Callback

You can see that the simplification effect is very obvious.

The same applies to web pages or nodejs, etc.

Related recommendations:

WeChat applet getUserInfo callback detailed explanation

jQuery callback method usage detailed explanation

Analysis of PHP callback function

The above is the detailed content of WeChat applet Promise simplified callback example sharing. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

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

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

Mango tv member account sharing 2023 Mango tv member account sharing 2023 Feb 07, 2024 pm 02:27 PM

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

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 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

See all articles