Home >WeChat Applet >Mini Program Development >Proxy encapsulates asynchronous calls of small programs
I wrote last time:
For those who didn’t read last time, here it is: Use
async/await
function wxPromisify(fn) { return async function(args) { return new Promise((resolve, reject) => { fn({ ...(args || {}), success: res => resolve(res), fail: err => reject(err) }); }); }; } export function toAsync(names) { return (names || []) .map(name => ( { name, member: wx[name] } )) .filter(t => typeof t.member === "function") .reduce((r, t) => { r[t.name] = wxPromisify(wx[t.name]); return r; }, {}); }
// pages/somepage/somepage.jsimport { toAsync } = require("../../utils/async"); // ...const awx = toAsync(["login", "request"]);await awx.login();await awx.request({...});# in WeChat mini program ##Isn’t this already encapsulated? This time I wrote a different package. Because it is really annoying to write multiple toAsync calls in a small program!
// utils/asyncjsfunction wxPromisify(fn) { ... } // 前面已经定义过了export function asyncProxy(target) { return new Proxy(target, { cache: {}, get(it, prop) { const aFn = this.cache[prop]; if (aFn) { return aFn; } const v = it[prop]; if (typeof v !== "function") { return v; } return this.cache[prop] = wxPromisify(v); } }); }
// app.jsimport { asyncProxy } from "./utils/async"; App({ onLaunch: function() { wx.awx = asyncProxy(wx); // .... } })
// pages/somepage/somepage// ...const { awx } = wx;await awx.login();await awx.request({...});Explanation: Because awx is the wx object of the proxy, when calling awx.login(), the proxy's get(wx, "login" is actually called first ), find something to use instead of wx.login . According to the logic in the above code, first look for the result encapsulated using wxPromisify() from the cache. If there is one, return it directly; if not, first encapsulate it into a function of the Promise network, store it in the cache, and then return it. An intuitive description is probably like this:
awx.login(); ^^^^^^ get(wx, "login")Recommended tutorial: "
WeChat Public Account"
The above is the detailed content of Proxy encapsulates asynchronous calls of small programs. For more information, please follow other related articles on the PHP Chinese website!