This method is an asynchronous request encapsulated into synchronization request, together with authentication token, small micro-channel environment trial program that can modify the file ajax, their encapsulated, like for example with axios
Success using standard codes 200 to 300 and 304, can modify the need
After access synchronization task, each task to verify the token, are synchronous requests between each of the tasks, including token
/ * * * Synchronous flow request * token to verify each interface * currying add synchronization tasks * resolve to return RES, cb * Reject return RES, cb * by task interrupt test * by success or failure callback function tests * * Task Flow task access the currying function as currying (() => {}) -> * as currying begin () function g into the circulation method of asynchronous synchronous execution -> * rp execute asynchronous method invocation function package new new Promise return -> * rp Analyzing the function execution processing token status * / const regeneratorRuntime = the require ( './ Regenerator-Runtime / runtime.js') // Runtime class const errorMessage =' service is busy, try again later ' // public tips const successMessage =' complete ' // public tips class the SuperClass { constructor () { Object.assign ( the this , {}) // interfaces awaiting execution of the this .wait = [] } // Promise request interface RP (the opts, = skipToken to false ) { const _t is = the this , Data = opts.data || {} @ applet identification data.source = opts.sourceFlag data.source:?. 1 ; // request information console.group ( `request Interface --- $ {}` opts.url); the console.log ( 'interface information' , { the opts, skipToken }) console.groupEnd (); return new new Promise (function(resolve, reject) { opts.header = { "Content-Type": "application/json;charset=utf-8", //不需要走token的接口 Authorization: !!opts.skipToken ? '' : (wx.getStorageSync('token') || '') } wx.request({ url: '域名' + opts.url, data: data, header: opts.header, method: opts.method, dataType: 'json', responseType: 'text', success: function(res) { const { Data } = RES // successful token 400 is a token collecting failure processing failures inner code fails merge processing function token IF (Data && (_t.successCode ({ code: data.code }) || data.code == 400 )) { Resolve (Data) } the else { // other unpredictable for the failure Reject (Data) } }, fail: function (RES) { Reject (res.data) }, complete: function (RES) { // complete stop loading wx .hideToast () opts.complete && opts.complete (res.data) } }) }) } // null parameter Throws paramNoNull () { the throw new new Error ( 'Missing Parameter' ) } // G function of the async G () { the let _t is = the this , // interrupt task isbreak =!. 1 for (the let [I, V] of _t.wait.entries ()) { const R & lt = the await V (). the catch ((RES) => { // collect all Tip uniform implementation of mistake or error callback const { cb, the Message } = RES //Synchronous stream is interrupted _t.clearWait () isbreak = 0! ; // no callback function performs error 'cb' in RES cb (): (wx.factory._toast (the Message ||? ErrorMessage)) }) // task execution successful IF (R & lt !! === Object && && r.constructor !! Object.keys (R & lt) .length) { const { RES: { code, Data, Message }, CB } = R & lt // layer function processes success status IF (_t.successCode ({ code })) { }CB && !! CB () // synchronous flow execution completion IF ((I +. 1) == _t.wait.length) { _t.clearWait () wx.factory._toast (Message || successMessage) } } the else { / / synchronization stream interrupt _t.clearWait () isbreak =! 0 wx.factory._toast (Message || errorMessage) } } IF (!! isbreak) { bREAK } } // Clear task clearWait () { the this .wait = [] } // currying as currying () { const _t is = the this return ( function (Arg) { IF (arg.length === 0 ) { _t.g () } the else { [] .push.apply (_t.wait, Arg); } }) (arguments) } // success code successCode ({ code = 404 }) { return (code> = code 200 is && <300) code || == 304 } } // super-class, multiple inheritance const = Sup Decorator => class the extends Sup { constructor(...args) { super(...args) } //获取token接口 greatetoken(opts) { let codeOPts = JSON.parse(JSON.stringify(opts)); codeOPts.url = `/getToken` codeOPts.method = `POST` codeOPts.data = { appIds: "xx", userId: 5 } return super.rp(codeOPts, true).then((res) => { const { code, data } = res IF (super.successCode ({ code: cb.code })) { IF (Data && !! !! data.token) { // global token storage of Storage wx.setStorageSync ( 'token' , data.token) } the else { wx.factory._toast ( 'Get token failed' ) } } the else { wx.factory._toast ( 'Get token failed' ) } }). the catch (() => { wx.factory._toast ( 'Get token failed ' ) }) } / * * * public class interfaces * Synchronization request returns Promise * request retransmission request token premise expired empty * / the async Send (the opts) { const token = wx.getStorageSync ( 'token' ), sendFun = (the opts) => { // conversion http request catch capturing the reject show promise only console interface level error printing operation flows other function g (callback, suggesting) return super.rp (the opts). the catch (RES => { // here show RP reject error console.group ( `% c request interface --- $ {opts.url} --- given `, 'Color: Red;' ); the console.log (` -> parameters `, { Data: opts.data }); the console.log ( ` -> return value`, { RES }); console.groupEnd (); // the error information to the function g which catch opts.fail && opts.fail (RES) }) }, successFun = the async (the opts) => { const CB = the await sendFun (the opts) // the information to the success function g which super.successCode ({ code: cb.code }) && && opts.success opts.success (CB) } IF (! opts.skipToken) { // need to request token IF (! token) { // token is empty token request directly initiate the await the this .greatetoken (the opts) successFun the await (the opts) } the else { const CB = the await sendFun (the opts) IF (!! CB) { // case expired token 400 only in the presence of the token will have merged aging treatment IF (== cb.code 400 ) { the await the this .greatetoken (the opts) the await successFun (the opts) } the else { // the information to the success function g which super.successCode ({ code: cb.code }) && && opts.success opts.success (CB ) } } } } the else { await successFun(opts) } } post(opts) { opts.method = "POST"; this.send(opts) } get(opts) { opts.method = "GET"; this.send(opts); } } class Http extends decorator(SuperClass) { //子类 constructor() { //继承参数 super() } } export default new Http
The introduction of the way, the global call
import Http from './public/js/request'
wx.http = Http
Call execution, can bind function parameter passing
success for a successful return, the value of the inflow code value determination task code to distinguish resolve
fail to return failed reject
The method of execution is complete
Page({ onLoad(){ wx.http.currying(this.a.bind(this, { a: 1 })) //进行传参bind wx.http.currying(this.b) wx.http.currying() }, a() { const _t = this wx.factory._toast('加载a信息中...', 6000) return new Promise((resolve, reject) => { wx.http.post({ url: 'a', data: { "params": { id:33 } }, success(res) { resolve({ res,
cb()=>{} }) }, fail(res) { reject({ res,
cb()=>{} }) } }) }) }, b() { const _t = this wx.factory._toast('加载b信息中...', 6000) return new Promise((resolve, reject) => { wx.http.post({ url: 'b', data: { id:33 }, success(res) { resolve({ res }) }, fail(res) { reject({ res }) } }) }) } })