Home  >  Article  >  WeChat Applet  >  How to perform asynchronous processing in WeChat applet

How to perform asynchronous processing in WeChat applet

angryTom
angryTomforward
2020-03-18 10:07:208567browse

This article introduces the asynchronous processing method in WeChat applet development. I hope it will be helpful to friends who are learning WeChat applet development!

How to perform asynchronous processing in WeChat applet

How the WeChat applet performs asynchronous processing

The WeChat applet performs asynchronous processing through wx.request, using It is indeed a lot of inconvenience and cannot be tolerated. Fortunately, the mini program supports ES6 syntax, so it can be slightly modified using promises.

Recommended learning: Small program development

Page({
    data: { 
        myData:
    },
    // loadMyData函数用于打印myData的值 
    loadMyData () { 
        console.log(获取到的数据为: + this.data.myData)
    }, 
    // 生命周期函数onload用于监听页面加载
    onload: function () { 
        wx.request({
            url: https://api, 
            // 某个api接口地址 
            success: res => { 
                console.log(res.data) 
                this.setData({ 
                    myData: res.data 
                }) 
            console.log(this.data.myData) 
            }
        }) 
        // 调用之前的函数 
        this.loadMyData() 
    } 
})

Then we will get the result like this on the console:

How to perform asynchronous processing in WeChat applet

This is actually a very simple asynchronous problem. wx.request is an asynchronous request. JS will not wait for wx.request to be executed before continuing, so JS will execute this.loadMyData() first in order, and wait for the server to return the data. , loadMyData() has been executed long ago, and of course the value has not been obtained.

In fact, we only say "return" in the synchronous process. There is no concept of "return" in asynchronous (or asynchronous return is meaningless). Asynchronous corresponds to "callback", that is, for a For asynchronous functions, we should pass in a "callback function" to receive the results.

Initial solution: receiving results through callbacks

The simplest solution is to write the function that needs to use asynchronous data in the callback:

onload: function () { 
    wx.request({ 
        url: https://api,
        // 某个api接口地址 
        success: res => { 
            console.log(res.data) 
            this.setData({ 
            myData: res.data 
        }) 
        console.log(this.data.myData) 
            // 把使用数据的函数写在回调函数success中 
            this.loadMyData() 
        } 
    }) 
}

And we found that the network request wx.request of the WeChat applet is also in the form of relying on a callback function, similar to the previous $.ajax. It also has disadvantages when the logic is complex and the page execution order is required. obviously. Fortunately, the mini program supports ES6, so we can embrace Promise as much as we can!

Use Promise to wrap wx.request

Promise simply means that it can separate asynchronous execution logic and result processing, eliminating the need for Layers of nested callbacks make the processing logic clearer.

/** 
* requestPromise用于将wx.request改写成Promise方式 
* @param:{string} myUrl 接口地址 
* @return: Promise实例对象 
*/ 
const requestPromise = myUrl => {
    // 返回一个Promise实例对象 
    return new Promise((resolve, reject) => { 
        wx.request({
            url: myUrl, 
            success: res => resolve(res) 
        })
    })
}
// 我把这个函数放在了utils.js中,这样在需要时可以直接引入 
module.exports = requestPromise

Try using it again now:

// 引用模块
const utilApi = require(../../utils/util.js)
Page({
    ... 
    // 生命周期函数onload用于监听页面加载 
    onLoad: function () {
        utilApi.requestPromise(https://www.bilibili.com/index/ding.json) 
        // 使用.then处理结果 
        .then(res => { 
            console.log(res.data) this.setData({
            myData: res.data
        }) 
        console.log(this.data.myData) 
        this.loadMyData() 
        }) 
    } 
})

The result is the same as using the callback function. When there are multiple asynchronous requests, just use .then(fn) to process them directly, and the logic is clear.

Of course, I only wrote the simplest Promise function here, which is not complete. A more complete Promise-based wx.request will be improved upon future business needs. In addition, various small program development frameworks also have ready-made promise APIs, which are ready to use.

PHP Chinese website, a large number of programming tutorials and website construction tutorials, welcome to learn!

The above is the detailed content of How to perform asynchronous processing in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:zixun.jisuapp.cn. If there is any infringement, please contact admin@php.cn delete