使用async + await将uni-app中的异步请求同步化
问题背景
在uni-app中,uni.request等许多接口都是异步的,直接使用可能会导致页面渲染完毕时,数据还未成功获取的情况,必须手动触发方法或页面修改后重新渲染才能重新获取数据。
解决方法
总体思路就是使用
async+await,使异步问题同步化。需要 注意 的是,这里需要借助Promise构造函数将
uni.request封装一下。
代码
//获取code
getCode: function(){
return new Promise((resolve, reject) => {
//获取微信小程序 OPENID
uni.login({
success: (login_res) => {
if(login_res.errMsg == 'login:ok'){
uni.setStorageSync("code",login_res.code);
resolve(login_res.code);
}
},
fail: (err) => {
reject('err')
}
});
});
},调用时
//闭包省事
(async function() {
await that.getCode();
console.log('code->',uni.getStorageSync('code'));
})();-----
this.$store
.dispatch("account/userLogin", this.loginForm)
.then(async () => {
await this.$store.dispatch("session/init");
this.isSubmitLoading = false;
this.$uni.reLaunch({
url: '/pages/index/index'
});
})
.catch(() => {
this.isSubmitLoading = false;
});