/** * 微信wx.Request 请求接口的附加值 */ export interface PromiseWxResponse<T> extends Promise<T> { /** * Response对象 */ wxResult?: WechatMiniprogram.RequestSuccessCallbackResult, /** * 微信wx.Request 的实例 */ wxRequestTask?:WechatMiniprogram.RequestTask } /** * 统一的HTTP请求入口 * @param options {string | RequestOption} url 接口地址 或者 RequestOption 对象 * @param needLoginCallback 登录拦截的callback方法。当接口数据返回成功、且code是401时,将执行needLoginCallback * @returns {PromiseWxResponse<*> */ export const request = (options: RequestWxOption): PromiseWxResponse<any> => { const promise: PromiseWxResponse<any> = new Promise((resolve, reject) => { const requestTask:WechatMiniprogram.RequestTask = wx.request(<WechatMiniprogram.RequestOption>{ url: options.url, method: options.method, data: options.data, header: options.header, success: (result: WechatMiniprogram.RequestSuccessCallbackResult) => { promise.wxRequestTask = requestTask; promise.wxResult = result; resolve(data);e { } }, fail: (result: WechatMiniprogram.GeneralCallbackResult) => { promise.wxRequestTask = requestTask; reject(result); } }); }); return promise; };
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[代码]
2021-01-08