微信小程序为了提高用户体验,提供的api大部分都是异步操作,除了数据缓存操作里面有一些同步操作。是提高了用户体验,但是在开发的时候,
就有点坑了,例如我要写一个公共方法,发起网络请求,去后台去一些数据,成功之后,再做一些操作,但是由于wx.request是异步请求,就会
导致,网络请求还没结束,就会执行后面的代码,从而引起异常,怎么解决这种异步导致的问题呢,当然是promise了。看例子:
公共common.js里封装了一个得到用户实体的方法:
//发起请求,得到用户实体
function GetUserEntity() {
wx.request({
url: http_config.getUserDetail,
data: {
Sha1OpenId: wx.getStorageSync('LoginSessionKey')
},
success: (res) => {
let result = res.data.data;
console.log(result)
return result;
},
fail: () => {
return "系统异常,请重试!"
}
})
}
module.exports.GetUserEntity = GetUserEntity
然后在另一个js中调用这个方法,得到用户实体成功之后,在进行一系列操作:
const com = require(`${root_path}/utils/common.js`)
//在方法中进行一下操作
let userEntity = com.GetUserEntity();
console.log(userEntity.Sex)
console.log("得到实体之后进行的操作")
执行之后会发现,程序报错
明明实体用有Sex这个属性,为什么报错,这就是异步请求造成的问题,请求还没返回值,下面的代码已经执行了。
解决办法:利用promise
网络请求改成:
function GetUserEntity() {
return new Promise(function (resolve, reject) {
wx.request({
url: http_config.getUserDetail,
data: {
Sha1OpenId: wx.getStorageSync('LoginSessionKey')
},
success: (res) => {
let result = res.data.data;
resolve(result) ;
},
fail:()=>{
reject("系统异常,请重试!")
}
})
})
}
请求方法改成:
comm.GetUserEntity().then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
简单记忆:resolve 返回,之后代码走then,reject返回,那么代码就会走catch。
我们可以把执行GetUserEntity方法之后要执行的代码放在then中,如果GetUserEntity中发起的请求出错那么程序就会通过reject返回信息,
那么我们可以再catch中做相应的处理。