//封装的方法
requestFunction:function(url,params){
var obj;
wx.request({
url: url,
data: params,
method: ‘get’,
header: {
‘content-type’: ‘application/x-www-form-urlencoded’
},
success: function (result) {
console.log(“返回值:”+result.data)
obj = result.data
}
})
return obj;
}
----------------但是现在的问题,这个是异步请求,我在调用方法获取到这个返回值的时候,返回值还没被赋值,大神们有没有啥解决方法
----------------不会同步。。。
import regeneratorRuntime from '../utils/regenerator-runtime/runtime-module' const wxRequest = async (url, params = {}) => { Object.assign(params, {token: wx.getStorageSync( 'token' )}) let data = params.query || {} wx.showLoading({ title: '加载中...' , }) let res = await new Promise((resolve, reject) => { wx.request({ url: url, method: params.method || 'GET' , data: data, header: { 'Content-Type' : 'application/json' , 'token' : params.token || '' }, success: (res) => { if (res && res.statusCode == 200 && res.data) { resolve(res.data) } else { reject(res) } }, fail: (err) => { wx.showModal({ title: '网络出错,请稍后重试' , showCancel: true }) reject(err) }, complete: (e) => { wx.hideLoading() } }) }) return res } module.exports = { wxRequest } |
用了async/await。仅供参考。
我是这样封装的
/** * 封装 post 请求为 Promise * [@param](/user/param) url * [@param](/user/param) data * [@param](/user/param) header * [@returns](/user/returns) {*|Promise<any>} */ post: function (url, data, header = {}) { if ( this .globalData.deviceSerialNumber) { header = {...header, 'device-serial-number' : this .globalData.deviceSerialNumber}; } return url && data && new Promise((resolve, reject) => { wx.request({ url: url, method: 'POST' , data: data, header: { 'content-type' : 'application/json' , // 微信默认就是 ...header }, success: function (res) { resolve(res); }, fail: function (res) { reject(res); } }); }); } |
网络请求是异步的,直接同步返回肯定出错。想省事,就把你这个方法加一个参数——回调函数即可。
requestFunction: function (url,params,callback){ wx.request({ url: url, data: params, method: 'get' , header: { 'content-type' : 'application/x-www-form-urlencoded' }, success: function (result) { console.log( "返回值:" +result.data) callback(result.data) } }) } |
// 仅供参考,return返回的是requestTask对象 request: function ({ path, params = {}, cb, method = 'GET' , header = { 'Accept' : 'application/json' }, fail }) { var that = this return wx.request({ url: that.yuming + path, method: method, data: params, header: header, success: function (res) { typeof cb == "function" && cb(res) }, fail: function (err) { that.hideLoading() console.log( 'err' , err) typeof fail == "function" && fail(err) if (err.errMsg == "request:fail abort" ) return wx.showToast({ title: '请求出错,请稍候再试' , image: '/images/err.png' , duration: 1000, mask: true , }) } })
|