wx.request 经 Promise 封装后,如何拿到requestTask
大家会用 promise 将 wx.request 包装一层。但经过这么一层包装后,就拿到不到 requestTask,从而调用不了 abort 方法。大家都是如何解决的?
代码来自:https://www.kancloud.cn/xiaoyulive/wechat/526990 [代码]class Request {[代码][代码] [代码][代码]constructor (parms) {[代码][代码] [代码][代码]this[代码][代码].withBaseURL = parms.withBaseURL[代码][代码] [代码][代码]this[代码][代码].baseURL = parms.baseURL[代码][代码] [代码][代码]}[代码][代码] [代码][代码]get (url, data) {[代码][代码] [代码][代码]return[代码] [代码]this[代码][代码].request([代码][代码]'GET'[代码][代码], url, data)[代码][代码] [代码][代码]}[代码][代码] [代码][代码]post (url, data) {[代码][代码] [代码][代码]return[代码] [代码]this[代码][代码].request([代码][代码]'POST'[代码][代码], url, data)[代码][代码] [代码][代码]}[代码][代码] [代码][代码]put (url, data) {[代码][代码] [代码][代码]return[代码] [代码]this[代码][代码].request([代码][代码]'PUT'[代码][代码], url, data)[代码][代码] [代码][代码]}[代码][代码] [代码][代码]request (method, url, data) {[代码][代码] [代码][代码]const vm = [代码][代码]this[代码][代码] [代码][代码]return[代码] [代码]new[代码] [代码]Promise((resolve, reject) => {[代码][代码] [代码][代码]wx.request({[代码][代码] [代码][代码]url: vm.withBaseURL ? vm.baseURL + url : url,[代码][代码] [代码][代码]data,[代码][代码] [代码][代码]method,[代码][代码] [代码][代码]success (res) {[代码][代码] [代码][代码]resolve(res)[代码][代码] [代码][代码]},[代码][代码] [代码][代码]fail () {[代码][代码] [代码][代码]reject({[代码][代码] [代码][代码]msg: [代码][代码]'请求失败'[代码][代码],[代码][代码] [代码][代码]url: vm.withBaseURL ? vm.baseURL + url : url,[代码][代码] [代码][代码]method,[代码][代码] [代码][代码]data[代码][代码] [代码][代码]})[代码][代码] [代码][代码]}[代码][代码] [代码][代码]})[代码][代码] [代码][代码]})[代码][代码] [代码][代码]}[代码][代码]}[代码] [代码]const request = [代码][代码]new[代码] [代码]Request({[代码][代码] [代码][代码]baseURL: [代码][代码]'http://test'[代码][代码],[代码][代码] [代码][代码]withBaseURL: [代码][代码]true[代码][代码]})[代码] [代码]module.exports = request[代码]