Proxy 封装微信小程序的异步调用

上回写到:

没看上回的同学,在这里

// utils/async.js

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.js

import { toAsync } = require("../../utils/async");

// ...

const awx = toAsync(["login", "request"]);
await awx.login();
await awx.request({...});

这不已经封装过了吗?

这回写的是不一样的封装。因为,一个小程序里要写好多个 toAsync 调用,真的很烦呐!


能不能一次封装,到处调用?能!把所有用到的方法都在初始化的时候封装起来。可是,难免会有遗漏。

能不能一次封装,到处调用,还不需要初始化?

能!祭出 Proxy 大神:

// utils/asyncjs

function 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.js
import { asyncProxy } from "./utils/async";

App({
    onLaunch: function() {
        wx.awx = asyncProxy(wx);
        // ....
    }
})
// pages/somepage/somepage
// ...
const { awx } = wx;
await awx.login();
await awx.request({...});

解释:

因为 awx 是代理的 wx 对象,调用 awx.login() 的时候,实际是先调用代理的 get(wx, "login"),找到用来代替 wx.login 的东西。

根据上面代码里的逻辑,先从 cache 里找使用 wxPromisify() 封装的结果,若有,直接返回;若没有,先封装成 Promise 网络的函数,存入 cache,再返回。

直观一点描述,大概是这样:

扫描二维码关注公众号,回复: 10629711 查看本文章
awx.login();
   ^^^^^^
   get(wx, "login")

最后出个题:像 wx.request() 这种原本就有返回值的情况,该如何封装呢?


喜欢此文,点个**

猜你喜欢

转载自blog.51cto.com/jamesfancy/2486056
今日推荐