p-saga
TypeScript icon, indicating that this package has built-in type declarations

1.0.14 • Public • Published

p-saga

基于 Promise 封装的常用处理异步任务的方法。

方法

map

异步任务按顺序逐个执行,全部完成后返回全部结果。

reduce

异步任务逐个执行,每个任务会接收上个任务的执行结果和序号为参数,可以设置初始值,全部完成后返回全部结果。

batch

按固定任务数量并发,逐批次完成全部任务,全部完成后返回全部结果。

outburst

按照指定数量同时启动第一批,每个任务完成后启动一个剩余任务,直至全部完成返回全部结果。

使用

import { map, reduce, batch, outburst } from "p-saga";

map(
    Array.from({ length: 20 }).map(
        () => (page: number) =>
            fetch(new Request(`/mock/list?page=${page}&size=20`), {
                method: "GET",
            })
    )
);

全局使用

// 入口文件
import { map, reduce, batch, outburst } from "p-saga";

if ("defineProperties" in Object) {
    Object.defineProperties(Promise, {
        map: {
            value: map,
        },
        reduce: {
            value: reduce,
        },
        batch: {
            value: batch,
        },
        outburst: {
            value: outburst,
        },
    });
} else {
    Promise.map = map;
    Promise.reduce = reduce;
    Promise.batch = batch;
    Promise.outburst = outburst;
}
// typings.d.ts

declare interface PromiseConstructor {
    map: <T = any>(
        tasks: Array<(index: number) => T | Promise<T>>
    ) => Promise<T[]>;
    reduce: <T = any, P = any>(
        tasks: Array<(index: number, preValue?: T | P) => T | Promise<T>>,
        preValue?: P
    ) => Promise<T[]>;
    batch: <T = any>(
        count: number,
        tasks: Array<(index: number, batchIndex: number) => T | Promise<T>>
    ) => Promise<T[]>;
    outburst: <T = any>(
        count: number,
        tasks: Array<(index: number) => T | Promise<T>>
    ) => Promise<T[]>;
}

Package Sidebar

Install

npm i p-saga

Weekly Downloads

0

Version

1.0.14

License

MIT

Unpacked Size

24.7 kB

Total Files

8

Last publish

Collaborators

  • magickeyyy