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) } })
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); }); } }
Let’s look at the simplest one first:
// 获取系统信息 wx.getSystemInfo({ success: res => { // success console.log(res) }, fail: res => { } })
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=>{ })
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) })
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!

Vue是一款流行的前端框架,在开发应用时经常会遇到各种各样的错误和问题。其中,Uncaught(inpromise)TypeError是常见的一种错误类型。在本篇文章中,我们将探讨它的产生原因和解决方法。什么是Uncaught(inpromise)TypeError?Uncaught(inpromise)TypeError错误通常出现在

在日常生活中,我们常常会遇到承诺与兑现之间的问题。无论是在个人关系中,还是在商业交易中,承诺的兑现都是建立信任的关键。然而,承诺的利与弊也常常会引起争议。本文将探讨承诺的利与弊,并给出一些建议,如何做到言出必行。承诺的利是显而易见的。首先,承诺可以建立信任。当一个人信守承诺时,他会让别人相信自己是一个可信赖的人。信任是人与人之间建立起的纽带,它可以让人们更加

Promise.resolve()详解,需要具体代码示例Promise是JavaScript中一种用于处理异步操作的机制。在实际开发中,经常需要处理一些需要按顺序执行的异步任务,而Promise.resolve()方法就是用来返回一个已经Fulfilled状态的Promise对象。Promise.resolve()是Promise类的一个静态方法,它接受一个

利用Promise对象,把普通函数改成返回Promise的形式,解决回调地狱的问题。明白Promise的成功失败调用逻辑,可以灵活的进行调整。理解核心知识,先用起来,慢慢整合吸收知识。

本篇文章给大家带来了关于微信小程序的相关问题,其中主要介绍了如何在小程序中用公众号模板消息,下面一起来看一下,希望对大家有帮助。

promise对象状态有:1、pending:初始状态,既不是成功,也不是失败状态;2、fulfilled:意味着操作成功完成;3、rejected:意味着操作失败。一个Promise对象一旦完成,就会从pending状态变为fulfilled或rejected状态,且不能再改变。Promise对象在JavaScript中被广泛使用,以处理如AJAX请求、定时操作等异步操作。

前端js学习中,让大家最难受的就是异步的问题,解决异步、回调地狱等问题时你必须得学会promise,对于多数前端程序员来说promise简直就是噩梦,本篇文章就是从通俗易懂的角度做为切入点,帮助大家轻松掌握promise


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
