问题:
小程序希望一进来就调用uni.login接口进行登录(在app.vue上onLaunch函数进行联调,原因是这个接口是页面进来先执行的),然后把获取回来的code进行联调接口把用户身份提交给后台。由于接口联调是异步的,很难控制页面接口的顺序。
假设首页有获取首页的接口,由于请求是异步的,如果想让app.vue先执行onLaunch再执行其他函数的话需要把onLaunch函数跟要执行的函数由异步变成同步,操作如下:
1、main.js
// 让app的onLaunch先执行,主要是用来进行登录
Vue.prototype.$onLaunched = new Promise(resolve => {
Vue.prototype.$isResolve = resolve
})
2、app.vue
onLaunch(options) {
uni.login({
success: (res) => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
let wxCode = res.code;
uni.request(
{
}
)
}
})
}
2、需要进行把异步变成同步的接口
async onShow() {
await this.$onLaunched;
this.getList();// 接口
console.log("index");
},
// 这样就可以把异步变成同步了