场景如下:现有一个方法需要等待其他N个异步函数执行完毕后执行,callback麻烦的头大,翻了一波API原来小程序已经支持 async函数,那一切就好办了。
废话不多说,直接开始撸。。。
第一步:打开增强编译
第二部:直接撸代码,这里写了个🌰
wait:function() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('ajax请求等待') }, 2000) }) }, onLoad: async function(options) { let ajaxTime = await this.wait(); console.log(ajaxTime) let getIndex = this.getArrIndex(this.data.sexArray, 'other.其他'); console.log('异步执行后获取index:'+getIndex) this.setData({ sexindex: getIndex }) },
上面的执行顺序是:
先执行:this.wait(),进入函数体,然后进入等待
2秒后执行:console.log(ajaxTime)
下面的代码则按照基本的js执行顺序执行。