1 Star 3 Fork 1

RHQYZ / wxmini-promisify

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

wxmini-promisify

NPM Version NPM Download License GitHub Actions Test Status

微信官方已于 2019 年 7 月 16 日推出了小程序 API Promise 化独立的扩展库 miniprogram-api-promise,详情请参阅此链接

微信官方已于 2020 年 2 月 20 日在小程序基础库 2.10.2 中支持了 API Promise 形式调用,详情请参阅此链接

本库还会继续维护更新。


特性

  • 将微信小程序、微信小游戏、企业微信小程序中提供的基于回调函数的 API,转化为 Promise 形式(wx.func 将转换成同名的 wx.funcAsync 形式);
  • 可单独拷贝到项目中使用;
  • 支持 TypeScript;
  • 支持 uni-app、Taro 等多端框架,同时理论支持目前所有主流小程序运行时(如 QQ 小程序、支付宝小程序、钉钉小程序、抖音小程序、头条小程序、百度智能小程序等等);
  • 与微信小程序基础库(当前版本:3.0.0)同步更新。

用法

安装:

npm install @skit/wxmini-promisify

导入:

const $ = require('@skit/wxmini-promisify');

$.promisifyAll({
    env: wx, // (可选)运行时对象。默认值 wx。
    root: wx, // (可选)指定异步方法挂载到某个对象的属性上。默认挂载到 wx。
    extends: ['someNewApi'] // (可选)若基础库新增了某些 API 而本库尚未更新,可由此传入相应的方法名数组以转换成异步方法。
});

使用异步方法:

wx.loginAsync({ timeout: 5000 })
    .then((res) => {
        console.log('success', res);

        return wx.getUserProfileAsync({ desc: '获取用户资料' });
    })
    .then((res) => {
        console.log('success', res);

        return wx.requestAsync({
            method: 'GET',
            url: 'https://baidu.com'
        });
    })
    .then((res) => {
        console.log('success', res);
    })
    .catch((err) => {
        console.warn('fail', err);
    })
    .finally(() => {
        console.log('complete');
    });

/**
 * @example 以上示例代码等同于下方原生实现:
 */
wx.login({
    timeout: 5000,
    success: (res) => {
        console.log('success', res);

        wx.getUserProfile({
            desc: '获取用户资料',
            success: (res) => {
                console.log('success', res);

                wx.request({
                    method: 'POST',
                    url: 'https://example.com/api/login',
                    success: (res) => {
                        console.log('success', res);
                    },
                    fail: (err) => {
                        console.warn('fail', err);
                    },
                    complete: () => {
                        console.log('complete');
                    }
                });
            },
            fail: (err) => {
                console.warn('fail', err);
            },
            complete: () => {
                console.log('complete');
            }
        });
    },
    fail: (err) => {
        console.warn('fail', err);
    },
    complete: () => {
        console.log('complete');
    }
});

当然,上述异步代码你也可以转写为 async + await 的形式,这里不再赘述。


常见问题

1. wx.getFileSystemManagerwx.getUserCryptoManagerwx.createMapContextwx.createBLEPeripheralServer 等方法,如何支持异步?

这类 API 不会被 promisifyAll 异步化,但可以像下面这样单独使其异步化:

const fileSystemManager = wx.getFileSystemManager();
const openFileAsync = $.promisify(fileSystemManager.open);
openFileAsync({ filePath: 'myFilePath' });

2. wx.requestwx.uploadFilewx.downloadFilewx.connectSocket 等方法,如何获取原始方法的返回值?

这类 API 虽然是也是异步的,但原始方法却会有自己的返回值,通常会有两个用途,一是可以添加特定的事件侦听器(如 onProgressUpdate),二是可以调用特定的方法(如 abort)。

对于前者需求,可以像下面这样使用:

wx.requestAsync({
    method: 'GET',
    url: 'https://example.com',
    onHeadersReceived: (e) => {
        console.log('receive header', e.header);
    }
});

/**
 * @example 以上示例代码等同于下方原生实现:
 */
const requestTask = wx.request({
    method: 'GET',
    url: 'https://example.com'
});
requestTask.onHeadersReceived((e) => {
    console.log('receive header', e.header);
});

对于后者需求,本库暂时无法满足,你仍可以使用原生方法来实现。

3. 在 TypeScript 中如何使用?

tsconfig.json 中加入:

{
    "compilerOptions": {
        "types": [
            ...
            "@skit/wxmini-promisify"
        ],
        ...
    }
}

这样就可以获得 TypeScript 的代码智能提示和类型检查等特性了。

如果你将异步 API 挂载到了非 wx 对象上,那么可能还需要显式地声明类型:

let myRoot = {} as WechatMiniprogram.WxAsync;
$.promisifyAll({ root: myRoot });

技术选型对比

库或框架 侵入性 兼容性 扩展性 TypeScript 支持 多端支持
原生写法 ×
@skit/wxmini-promisify
miniprogram-api-promise × ×
wepy-promisify × ×
wx-extend ×
wx-promise-pro × ×
minapp-api-promise × ×

指标释义:

  • “侵入性”越低越好,从以下 2 个维度衡量:

    1. 是否需要调整原有业务代码;

    2. 是否污染全局变量或有其他副作用。

  • “兼容性”越高越好,从以下 4 个维度衡量:

    1. 是否支持低版本小程序基础库;

    2. 是否覆盖完整的 API(含有多入参、有返回值等特殊 API);

    3. 是否保留原本的 successfail 回调;

    4. 是否以 Promise.prototype.finally 的形式支持原本的 complete 回调。

  • "扩展性"越高越好,从以下 1 个维度衡量:

    1. 是否允许扩展新的 API。
MIT License Copyright (c) 2019-2023 RHQYZ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

为微信小程序、小游戏提供 TypeScript 支持,同时将其基于回调函数的异步 API 转化为 Promise 形式。 展开 收起
取消

发行版 (2)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/fudiwei/wxmini-promisify.git
git@gitee.com:fudiwei/wxmini-promisify.git
fudiwei
wxmini-promisify
wxmini-promisify
main

搜索帮助