Home  >  Article  >  WeChat Applet  >  How to use async/await syntax in WeChat applet (code example)

How to use async/await syntax in WeChat applet (code example)

不言
不言forward
2019-02-16 10:23:334062browse

The content of this article is about the method of using async/await syntax (code example) in WeChat applet. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

1. Add the package.json file to the WeChat applet project or directly npm init.

2. Add the regenerator package and version to package.json

`"devDependencies": {
"regenerator":"0.13.3"}`

3. WeChat Developer Tools-》Tools-》npm build

4.Introduce regeneratorRuntime in files that need to use async/await syntax

const regeneratorRuntime = require('regenerator-runtime')

5.Use async/await syntax

lifetimes: {
    attached:async function(){
      // 在组件实例进入页面节点树时执行
     let data= await req(this.properties.apiType);
     console.log(data)
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

You need to pay attention to the direction of this. For example, if you use arrow functions in the life cycle, you will lose this
or just like this

 lifetimes: {
    async attached(){
      // 在组件实例进入页面节点树时执行
     let data= await req(this.properties.apiType);
     console.log(data)
    },
    async detached() {
      // 在组件实例被从页面节点树移除时执行
     
    },
  },

In fact, it can be used globally in app.js require once.

Reference for this article: Basic Tutorial on WeChat Mini Program Development https://www.html.cn/study/20.html

The above is the detailed content of How to use async/await syntax in WeChat applet (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What does unity mean?Next article:What does unity mean?