npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wx-promise-all

v1.1.0-beta

Published

Extend WeChat miniprogram's api to surport promise

Downloads

2

Readme

wx-promise-all

Extend WeChat miniprogram's api to surport promise by adding an Async suffix. Please refer to the miniprogram official documentation for more information.

Features

  • Call WeChat miniprogram's api based on Promise style;
  • Add the finally method extension to the Promise;
  • Can set global default parameter;
  • Overload miniprogram's api.
  • Add interceptors before the api is called;
  • Add interceptors after the api is called;
  • Extend global miniprogram's api.

Installation

$ npm install --save wx-promise-all

Getting started

Call the method promisifyAll at the program entry (app.js), It only needs to be called once. It is very important to add an Async suffix after the currently used method.

// app.js
import { promisifyAll, promisify } from 'wx-promise-all';

// promisify all wx's api
promisifyAll({ provider:wx });
wx.getSystemInfoAsync().then(console.log).catch(console.error);

// promisify single api
promisify(wx.getSystemInfo)().then(console.log).catch(console.error);

output:

{ errMsg: "getSystemInfo:ok", model: "iPhone 6", … }

API Configurations

name|type|description|default ---|:--:|:--:|---: defaultOptions|Object|default configuration options|{} promisable|Boolean|can the api be promiseify|true before|Array|interceptors before api call|[] after|Array|interceptors after api call|[] extend|Object|extend promise|{}

Please set promisable to false if the api does not support asynchronous mode.

API

promisifyAll(options: PromiseOptions) : object

promisify all available provider's api and return a new api vender.

  • provider(object): api provider, such as 'wx'
  • suffix(string, optional): the suffix of asynchronous method, default is 'Async'.
  • globalKey(string, optional): the global api config key name, defaut is '$global'.
  • bound(boolean, optional): weather bind asynchronous method to provider, default is true.
  • integrated(boolean, optional): weather integrate other members to the return object, default is true.
  • config(object, optional): api configuration options
    • $global: global configuration options
    • apiName: specific api name

promisify(api:function, config : ApiConfig, name : string) : function

promisify single api.

  • api: a function to be promisify
  • config: api configuration options
  • name: the api function name, can be used for interceptor's argument.

Promise.prototype.finally

The finally method is always called, either correctly or unexpectedly.

wx.showLoadingAsync()
    .then(()=>wx.requestAsync({url:'http://www.baidu.com'}))
    .then(console.log)
    .catch(console.error)
    .finally(wx.hideLoadingAsync)

output:

{data:"<!DOCTYPE html>↵<html class=""><!--STATUS OK--><he…ript><div id="bgContainer" ></div></body></html>", header: {…}, statusCode: 200, message: "request:ok"}

Set global configuration

Use $global to set global common configuration.

import { promisifyAll, ApiConfig } from 'wx-promise-all';

const replaceMessage = (result, param) => {
    if (result && result.errMsg) {
        result.message = result.errMsg;
        // delete result.errMsg;
    }
    return result;
};
promisifyAll({
    provider: wx, 
    config: {
        $global: new ApiConfig({
            // replace errorMsg with message field.
            after: [{ success: replaceMessage, fail: replaceMessage }]
        })
    }
});
wx.getSystemInfoAsync().then(console.log).catch(console.error);

output:

{ message: "getSystemInfo:ok", model: "iPhone 6", … }

Set default parameter

Use defaultOptions to set default parameters.

import { promisifyAll } from 'wx-promise-all';

promisifyAll({
    provider: wx, 
    config: {
        showModal:{
            // set default parameters for showModal
            defaultOptions: {
                title: 'default title',
                cancelColor: '#ff0000',
                confirmColor: '#00ff00',
            },
        }
    }
});

Overload global api

Use the before interceptors to modify the request parameters to implement method overloading.

import { promisifyAll, ApiConfig } from 'wx-promise-all';

promisifyAll({
    provider: wx, 
    config: {
        navigateTo: new ApiConfig({
            // overload navigateTo
            before: [{ success: p => typeof p === 'string' ? { url: p } : p }]
        })
    }
});
// The following two ways are equivalent
wx.navigateToAsync({ url : 'path' });
wx.navigateToAsync('path');

Complex example

Compatible with different versions of the api requestPayment's cancellation method, and collected formId when the payment is completed.

It is worth mentioning that the second parameter can be used to get the request parameters in after interceptors, and the third parameter is api name.

import { promisifyAll, ApiConfig } from 'wx-promise-all';

const replaceMessage = (result, param, apiName) => {
    if (result && result.errMsg) {
        result.message = result.errMsg;
        delete result.errMsg;
    }
    return result;
};

promisifyAll({}
    provider: wx, 
    config: {
        $global: new ApiConfig({
            // replace errorMsg with message field.
            after: [{ success: replaceMessage, fail: replaceMessage }]
        }),
        requestPayment: new ApiConfig({
            after: [{
                success: (data, param) => {
                    // Compatible with different versions of the cancellation method
                    if (data.message === 'requestPayment:cancel') {
                        // add cancel field to determine if it has been cancelled
                        data.cancel = true;
                        return Promise.reject(data);
                    } else {
                        // get request parameters from sencond parameter
                        const formId = param.package;
                        // collectFormId(formId);
                        return data;
                    }
                },
                fail: error => {
                    if (error.message === 'requestPayment:fail cancel') {
                        error.cancel = true;
                    }
                    return Promise.reject(error);
                }
            }]
        }),
        // don't need promisify
        stopRecord: new ApiConfig({ promisable:false })
    }
});

Update log