让微信小程序支持async-await

async-await是ES7的语法,截止我写这篇文章为止,小程序还是不支持async-await语法的,所以需要使用regenerator这个库

在小程序开发工具中如果勾选es6转es5, 会报错:

1
ReferenceError: regeneratorRuntime is not defined

为了避免报错引入regenerator

引入步骤

  1. 在根目录下创建 lib 文件夹,并将 https://github.com/facebook/regenerator/tree/master/packages 里面的 regenerator-runtime 文件夹放进去。
    0004

  2. 如果出现错误Uncaught TypeError: Function(...) is not a functionruntime.js最后一段try..catch...删掉
    0005

使用方法

  1. 在需要使用的地方直接进入即可

    1
    import regeneratorRuntime from '../../utils/regenerator-runtime/runtime';
  2. 当有返回是promise时,可直接使用 async await

  3. 处理微信微信小程序原生Api可以使用promise包裹一层,该api可以暴露在app.js中并通过getApp()获取,也可以通过export import来实现。

在需要使用api 的页面中处理如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import regeneratorRuntime from '../../utils/regenerator-runtime/runtime';

Page({
async onLoad(options) {
console.log('执行删除token--开始')
await this.removeStorage('token');
console.log('执行删除token--结束')
},

removeStorage(key) {
return new Promise((resolve, reject) => {
wx.removeStorage({ key: key, success: resolve, fail: reject })
})
}
})

参考

https://blog.csdn.net/weixin_33755554/article/details/88760981
https://www.cnblogs.com/cckui/p/10231801.html