场景以下:现有一个方法须要等待其余N个异步函数执行完毕后执行,callback麻烦的头大,翻了一波API原来小程序已经支持 async函数,那一切就好办了。ajax
第一步:打开加强编译小程序
第二部:直接撸代码,这里写了个🌰异步
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
})
},
上面的执行顺序是:async
先执行:this.wait(),进入函数体,而后进入等待函数
2秒后执行:console.log(ajaxTime)this
下面的代码则按照基本的js执行顺序执行。spa