小程序的wx.request是一個異步的請求,剝奪了函數的return能力,在請求的時候需要傳入一個回調函數的參數,在嵌套回調的時候很容易發生回調地獄。
維護的成本高,代碼不夠簡潔
promise把函數的回調功能還回來了,可以使用將請求回來的結果直接return 也可以使用一個變量接收,這個變量可以傳到代碼的任何地方進行使用,在需要使用數據的地方使用.then()獲取數據,也可以結合async/await獲取數據進行下一步的操作
接下來看代碼
import { config } from '../config.js' const tips = { 1: '抱歉,出現了一個錯誤', 1005: 'appkey無效,請前往www.7yue.pro申請', 3000: '期刊不存在' } // 在request中使用對象的方式寫參數({url, data, method}),那么在調取的地方也可以使用這種方式傳參 class HTTP { request({ url, data = {}, method = 'GET' }) { // promise接收兩個參數 resolve reject return new Promise((resolve, reject) => { this._request(url, resolve, reject, data, method) }) } _request(url, resolve, reject, data = {}, method = 'GET') { wx.request({ url: config.api_base_url + url, data: data, method: method, header: { 'content-type': 'application/json', 'appkey': config.appkey }, success: (res) => { let code = res.statusCode.toString(); if (code.startsWith('2')) { // 返回code以2開頭 resolve(res.data) } else { reject() let error_code = res.data.error_code this._show_error(error_code) } }, fail: (err) => { reject() this._show_error(1) } }) } _show_error(error_code) { if (!error_code) { error_code = 1; } const tip = tips[error_code] wx.showToast({ title: tip ? tip : tips[1], icon: 'none', duration: 2000 }) } } export { HTTP }
調用