小程序大部分函数和数据库操作都是异步执行的,如果希望同步执行,需要用到async 和await这对基友,必须成对出现。
为了快速验证 async/await 可用,在 App.js 的 onLaunch() 事件函数中加一段代码:
(async () => {
const p = await new Promise(resolve => {
setTimeout(() => resolve("hello async/await"), 1000);
});
console.log(p);
})();
比如获取openid, 首先getOpenID需要借助promise实现,然后才可以使用async 和 await来同步
Page({
getOpenID(){
return new Promise((resolve,reject)=>{
wx.cloud.callFunction({
name:'getOpenid'
}).then(res=>{
let openid = res.result.openid;
resolve(openid);
}).catch(res=>{
reject(res);
})
});
},
/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
const openid = await this.getOpenID();
}
})
关于 async 和 await的使用可参照Promise的简单应用(微信小程序版)-解决异步嵌套调用_未知数-zyx的博客-优快云博客_微信小程序promise的用法