Promise simplified callbacks for small programs
This time I bring you the Promise simplified callback of the mini program. What are the precautions for the simplified callback of the mini program Promise? The following is a practical case, let's take a look.
Promise is a solution to asynchronous programming that is more reasonable and powerful than the 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.
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 isIn 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) } })
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.jsmodule.exports = (api) => { return (options, ...params) => { return new Promise((resolve, reject) => { api(Object.assign({}, options, { success: resolve, fail: reject }), ...params); }); } }
// 获取系统信息 wx.getSystemInfo({ success: res => { // success console.log(res) }, fail: res => { } })
const promisify = require('./promisify') const getSystemInfo = promisify(wx.getSystemInfo) getSystemInfo().then(res=>{ // success console.log(res) }).catch(res=>{ })
##getSystemInfo
You can see that there is one less indentation in the simplified callback, and the callback function is reduced from 9 lines to 6 OK.
The simplified effect of the callback pyramidThen 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) })
Simplification Callback
You can see that the simplification effect is very obvious.
The same applies to web pages or nodejs, etc.
ReferencePromise object
Source codepromisePage page of tomfriwel/MyWechatAppDemo
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
eslint configuration during React developmentVue enumeration type implementation of HTMLThe above is the detailed content of Promise simplified callbacks for small programs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

Vue is a popular front-end framework, and you often encounter various errors and problems when developing applications. Among them, Uncaught(inpromise)TypeError is a common error type. In this article, we will discuss its causes and solutions. What is Uncaught(inpromise)TypeError? Uncaught(inpromise)TypeError error usually appears in

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

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

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.

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.
