import { WxQueue } from "miniprogram-queue"; /// //@ts-ignore const RequestMQ = new WxQueue(wx.request); /** * fetch 封装 * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API * @param url 请求URL或者Request对象 * @param init 请求参数 */ export function fetch(url, init) { init = init || {}; const param = ((typeof url) !== 'object') ? { url, data: init.body, header: init.headers || {}, method: init.method, dataType: 'text' } : { url: url.url, data: url.json() || url.text() || url.body, method: init.method || url.method, header: Object.assign({}, url.headers, init.headers), dataType: 'text', }; return new Promise((resolve, reject) => { param.success = function (res) { var response = new wxHttpResponse(res); resolve(response); }; param.fail = reject; param.complete = init['complete']; RequestMQ.push(param); }); } class wxHttpResponse { constructor(res) { this.status = res.statusCode; this.headers = res.header; this.body = res.data; this.ok = res.statusCode >= 200 && res.statusCode < 300; this.bodyUsed = false; } /** * Copy */ clone() { return Object.assign(this); } arrayBuffer() { throw new Error("Method not implemented."); } blob() { throw new Error("Method not implemented."); } formData() { return new Promise((resolve, reject) => { let data = this.body; try { if (typeof data === "string") { data = JSON.parse(data); } const formData = new FormData(); for (let key in data) { formData.append(key, data[key]); } resolve(formData); this.bodyUsed = true; } catch (error) { reject(error); } }); } /** * to json as promise */ json() { return new Promise((resolve, reject) => { try { resolve(JSON.parse(this.body)); this.bodyUsed = true; } catch (error) { reject(error); } }); } /** * to string as promise */ text() { return new Promise((resolve, reject) => { try { resolve(this.body); this.bodyUsed = true; } catch (error) { reject(error); } }); } }