小程序onLaunch的异步问题解决方案

微信小程序app.js 中 onLaunch 与 index.js 中 onload 的异步执行问题 , 在同时触发的情况下 如何等待返回值而响应index中 onload的内容

  • 比如说 获取用户的openid或者凭证 在没返回需要的数据之前 index.js 的 onload会执行 从而导致后续的代码没有openid的支持 *

ES6中提供了一个promise方案是一个不错的解决方案

先做一个示例说明一下promise的用法

Promise是一个构造函数,自己身上有all、reject、resolve这几个眼熟的方法,原型上有then、catch等同样很眼熟的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function runAsync(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
console.log('执行完成');
resolve('随便什么数据');
}, 2000);
});
return p;
}
// 如何用?
runAsync(function(data){
console.log(data);
});

reject的用法

我们前面的例子都是只有“执行成功”的回调,还没有“失败”的情况,reject的作用就是把Promise的状态置为rejected,这样我们在then中就能捕捉到,然后执行“失败”情况的回调。看下面的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function getNumber(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
var num = Math.ceil(Math.random()*10); //生成1-10的随机数
if(num<=5){
resolve(num);
}
else{
reject('数字太大了');
}
}, 2000);
});
return p;
}

getNumber()
.then(
function(data){
console.log('resolved');
console.log(data);
},
function(reason, data){
console.log('rejected');
console.log(reason);
}
);

将promise结合到小程序中

promise下载地址
promiseCND

将压缩版本的源码直接复制出来 在小程序中创建一个promise.js的文件 直接粘贴进去 然后在app.js中引用

1
const Promise = require('utils/promise.js');

APP.js 中的代码

  • 将你本来写在 onLaunch 中的代码片段拿出来 重新写一个方法*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
login:function(){
let that = this;
return new Promise(function (resolve, reject) {
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
// console.log('获取用户登录凭证:' + code);
// ------ 发送凭证 ------
/*
* 通过code获取登录session
*/
wx.request({
url: 'xxx/login?code=' + res.code,
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res)
if (res.statusCode == 200) {
// 注意这里
resolve(res);
} else {
console.log(res.errMsg)
}
},
})
} else {
console.log('获取用户登录失败:' + res.errMsg);
}
}
})
})
}

index.js 中的代码

1
2
3
4
5
6
7
8
9
10
const { requestData } = require('../../utils/util');

onLoad: function (options) {
let _this = this;
app.login().then(function (res) {
let newDate = new Date();
// 修改到当前的时间
_this.changeNowTime();
})
},
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!