Home WeChat Applet WeChat Development Combination use of wx.request and Promise of WeChat applet

Combination use of wx.request and Promise of WeChat applet

Mar 19, 2018 pm 04:28 PM
promise Applets

This time I will bring you the combined use of wx.request and Promise in the WeChat applet. What are the precautions for the combined use of wx.request and Promise in the WeChat applet? The following is a practical case. Let’s take a look.

When using Promise, my multiple asynchronous codes usually look like this.

ajax(url, function (res){
    ajax(res.url, function(res) {
        ajax(res.url, function(res) {            if (res.status == '1') {
                ajax(res.url, function(res) {
                ...
                }
            }            else if (res.status == '2') {
                ajax(url2, function(res) {
                ...
            }
            ...
        }
    }
}
);
Copy after login
This kind of process is very labor-intensive and fragile, and the experience is very bad. Therefore, in this small program In order to have a better experience in the development, I started to use Promise.

The code is as follows. In this way, when our second request requires the first parameter judgment, we can no longer fall into callback hell,

// 小程序与后端情求接口
    let baseUrlPromise = 'https://xxx.com';    // 定义方法返回Promise参数,obj 为wx.request 方法中所需参数
    let req = function (obj) {      return new Promise(function (resolve, reject) {
        wx.request({
          url: baseUrlPromise + obj.url,
          data: obj.data,
          header: obj.header,
          method: obj.method == undefined ? "get" : obj.method,
          success: function (data) {            // 回调成功执行resolve            resolve(data)
          },
          fail: function (data) {            // 回调失败时
            if (typeof reject == 'function') {
              reject(data);
            } else {
              console.log(data);
            }
          },
        })
      })
    }    // 执行req 方法,传入第一个请求,
    let req1 = req({
      url: '第一次请求链接,与baseUrlPromise 相结合',
      data: {},
    })    // 当需要多次请求时加入
    req1.then(function (data) {
      console.log('promiseThen1')
      console.log(data);      return req({
        url: '第二次请求链接',
      })
    }).then(function (data) {
      console.log('promiseThen3')
      console.log(data);      return req({
        url:'第三次请求链接'
      })
   }).then(......).catch(function(data){
      console.log(PromiseCatch)
   })
Copy after login
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:

Using Vue instructions

Using JS closures

The above is the detailed content of Combination use of wx.request and Promise of 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

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)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

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

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

What should I do if I encounter Uncaught (in promise) TypeError in a Vue application? What should I do if I encounter Uncaught (in promise) TypeError in a Vue application? Jun 25, 2023 pm 06:39 PM

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

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

How to get membership in WeChat mini program How to get membership in WeChat mini program May 07, 2024 am 10:24 AM

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.

See all articles