wx.request有promise版的么
- 需求的场景描述(希望解决的问题)
登录后根据系统的用户id查询用户的数据,必须要登录接口执行完后才能调用查询接口,现在wx.request都是异步得的
- 希望提供的能力
wx.request,提供同步的的配置
3 回复
你可以自己封装一下最简单的方案就是
const request = opts => new Promise((success, fail)=>{ wx.request({...opts, success, fail}) }) |
const DEFAULT_REQUEST_OPTIONS = {
url: '',
data: {},
header: {
'Content-Type': 'application/json'
},
method: 'GET',
dataType: 'json'
}
let util = {
request (opt) {
let options = Object.assign({}, DEFAULT_REQUEST_OPTIONS, opt)
let {
url,
data,
header,
method,
dataType
} = options
try {
header.token = getApp().globalData.token
if (!header.token) {
header.token = wx.getStorageSync('token')
}
} catch (e) {
header.token = ''
}
return new Promise((resolve, reject) => {
wx.request({
url: basePath + url,
data: data,
header: header,
method: method,
dataType: dataType,
success: function (res) {
let result = res.data || {}
if (res.statusCode === 200) {
if (result.code === statusCode.OK) {
resolve(result)
} else if (result.code === statusCode.FAIL) {
reject(result)
} else if (result.code === statusCode.NOT_AUTHENTICATED || result.code === statusCode.USER_FAIL || result.code === statusCode.NO_USER) {
reject(result)
} else {
reject(result)
}
} else if (res.statusCode === 401) {
reject(result)
} else {
result = Object.assign({}, result, { msg: `服务器错误${res.statusCode}` })
reject(result)
}
},
fail: function (err) {
reject(err)
}
})
})
}
}