Proxy encapsulated micro-channel asynchronous call applet

On the back is written:

I did not fancy the students back in here !

// 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({...});

This package has not been yet?

This write-back is not the same package. Because, in a small program written to multiple toAsynccalls, really annoying na!


Can a package, call everywhere? can! All methods are used to encapsulate initialization time. However, inevitably there will be omissions.

Can a package, call around, you do not need to initialize?

can! Proxy resorted Great God:

// 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({...});

Explanation:

Because awxa proxy wxobject, call awx.login()time, call the agent actually is to get(wx, "login")find used instead of wx.loginthings.

The logic of the above code, start cachewas used to find wxPromisify()the results of encapsulation, if any, direct return; if not, the package as a function of the first network Promise, stored cache, and then return.

Intuitive point description, something like this:

awx.login();
   ^^^^^^
   get(wx, "login")

Finally, out of a question: like wx.request()the case of this had had a return value, how to package it?


Like this article, point a **

Guess you like

Origin blog.51cto.com/jamesfancy/2486056