微信小程序为了提升用户体验,提供的api大部分都是异步操做,除了数据缓存操做里面有一些同步操做。是提升了用户体验,可是在开发的时候,javascript
就有点坑了,例如我要写一个公共方法,发起网络请求,去后台去一些数据,成功以后,再作一些操做,可是因为wx.request是异步请求,就会html
致使,网络请求还没结束,就会执行后面的代码,从而引发异常,怎么解决这种异步致使的问题呢,固然是promise了。看例子:java
公共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("获得实体以后进行的操做")
执行以后会发现,程序报错api
明明实体用有Sex这个属性,为何报错,这就是异步请求形成的问题,请求还没返回值,下面的代码已经执行了。promise
解决办法:利用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((res) => { console.log(res) })
简单记忆:resolve 返回,以后代码走then,reject返回,那么代码就会走catch。
咱们能够把执行GetUserEntity方法以后要执行的代码放在then中,若是GetUserEntity中发起的请求出错那么程序就会经过reject返回信息,
那么咱们能够再catch中作相应的处理。
参考:https://www.cnblogs.com/zhihuama/articles/9143954.html
https://blog.csdn.net/qq_32786873/article/details/72179601