Proxy encapsulates asynchronous calls of small programs

hzc
Release: 2020-06-05 10:00:09
forward
2942 people have browsed it

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;
        }, {});
}
Copy after login
// pages/somepage/somepage.jsimport { toAsync } = require("../../utils/async");
// ...const awx = toAsync(["login", "request"]);await awx.login();await awx.request({...});
Copy after login
# 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!


Can it be encapsulated once and called everywhere? able! Encapsulate all methods used during initialization. However, there will inevitably be omissions.

Can it be encapsulated once and called everywhere without initialization?

able! Show off the Proxy master:

// 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);
        }
    });
}
Copy after login
// app.jsimport { asyncProxy } from "./utils/async";

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

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")
Copy after 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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!