在小程序的util.js中写入公共方法(如微信收取获取openid方法wxAuth)
const wxAuth = (data) => {
console.log(Date.parse(new Date()),data);
return test(data).then(runAsync1).then(runAsync2);
}
const test = (data) =>{
var p = new Promise(function (resolve, reject) {
setTimeout(function () {
//注意:一旦你把promise的状态定义了哪他的状态就不会再改变.
//比如我这里先写的resolve下面又跟着写了reject,reject的代码会执行但是promise的状态是不会变的就是reject
resolve({status:201,msg: data});
}, 2000);
})
return p;
}
const runAsync1 = (jj) =>{
var p = new Promise(function (resolve, reject) {
//做一些异步操作
setTimeout(function () {
console.log(Date.parse(new Date()),jj);
resolve("测试的数据1"+jj.msg);
}, 1500);
});
return p;
}
const runAsync2 = (hh) =>{
var p = new Promise(function (resolve, reject) {
//做一些异步操作
setTimeout(function () {
console.log(Date.parse(new Date()),hh);
resolve('随便什么数据2');
}, 1000);
});
return p;
}module.exports中把wxAuth暴露出去
module.exports = {
wxAuth: wxAuth,
}在需要的地方如Index.js中引用
const util = require('../../utils/util.js')onLoad:function(){
util.wxAuth('我是传参').then(res => {
console.log(Date.parse(new Date()),res);
}).catch(res => {
console.log(Date.parse(new Date()),res);
});
},若util的test中或runAsync1中或runAsync2中随时执行reject()方法,则在index.js中的catch中可以捕获;否则在index.js的then中捕获最后的异步返回参数“随便什么数据2”