小程序中使用es7语法 async (es7的 async 号称是解决回调的最终⽅案)是会报错的,需要进行如下配置:
- 在⼩程序的开发⼯具中,勾选 es6转es5语法
- 下载 facebook的regenerator库中的 regenerator/packages/regenerator-runtime/runtime.js
- 在⼩程序⽬录下新建⽂件夹 lib/runtime/runtime.js ,将代码拷⻉进去
- 在每⼀个需要使⽤async语法的⻚⾯js⽂件中,都引⼊(不能全局引⼊)
import regeneratorRuntime from '../../lib/runtime/runtime';
注意即使是按照上述步骤都整好,也会在某些旧的机型或者旧的小程序中报错,不适配,当要适配旧的手机等等,就需要重新改成 es6的promise.
目前暂时不考虑适配
按照上述步骤建好文件,然后是分类功能需要使用这项技术,因此只需要在分类的js文件中引入。
直接改造getCates 函数:
原来的getCates函数如下:
getCates() {
request({ url: '/categories' })
.then(res => {
this.Cates = res.data.message;
const obj = {time:Date.now(),data:this.Cates}
console.log(obj);
wx.setStorageSync('cates',obj);
// 构造左侧的大菜单数据
let leftMenuList = this.Cates.map(v=>v.cat_name);
// 构造右侧的商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent
})
})
}
改造之后
async getCates() {
// 1.使用es7的async await来发送请求
const res = await request({ url: '/categories' });
// 这里请求没有回来是不会继续往下执行的
this.Cates = res.data.message;
const obj = { time: Date.now(), data: this.Cates }
wx.setStorageSync('cates', obj);
// 构造左侧的大菜单数据
let leftMenuList = this.Cates.map(v => v.cat_name);
// 构造右侧的商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent
})
},