神刀安全网

Simple library to limit concurrently running promises

cwait

Simple library to limit concurrently running promises Simple library to limit concurrently running promises

cwait provides a queue handler ( TaskQueue ) and a wrapper ( Task ) for promises, to limit how many are being resolved simultaneously. It can wrap any ES6-compatible promises. This allows for example limiting simultaneous downloads with minor changes to existing code. Just wrap your existing "download finished" promise and use it as before.

This is a tiny library with no dependencies, usable both in browsers and Node.js.

Usage

Create a new TaskQueue passing it whatever Promise constructor you’re using (ES6, Bluebird, some other shim…) and the maximum number of promise-returning functions to run concurrently. Then just call queue.wrap(<function>) instead of <function> to limit simultaneous execution.

Simple Node.js example:

import * as Promise from 'bluebird'; import {TaskQueue} from 'cwait';  /** Queue allowing 3 concurrent function calls. */ var queue = new TaskQueue(Promise, 3);  Promise.map(list, download); // Download all listed files simultaneously.  Promise.map(list, queue.wrap(download))); // Download 3 files at a time.

See test/test.ts for some runnable code or run it like this:

git clone https://github.com/charto/cwait.git cd cwait npm install npm test

API

Class Task

Task wraps a promise, delaying it until some resource gets less busy.

Methods:

new( )

Task

▪ func

() => PromiseType

.start( )

PromiseType

Start the task immediately and call onFinish callback when done.

▪ onFinish

() => void

.delay( )

PromiseType

Wrap task result in a new promise so it can be resolved later.

▪ Promise

PromisyClass

.resume( )

PromiseType

Resolve the result of a delayed task and call onFinish when done.

▪ onFinish

() => void

Class TaskQueue

Methods:

new( )

TaskQueue

▪ Promise

PromisyClass

▪ concurrency number

.add( )

PromiseType

Add a new task to the queue. It will start when the number of other concurrent tasks is low enough.

▪ func

() => PromiseType

.wrap( )

(...args: any[]) => PromiseType

Wrap a function returning a promise, so that before running it waits until concurrent invocations are below this queue’s limit.

▪ func

(...args: any[]) => PromiseType

▫ thisObject ? any

Properties:

.concurrency number

Number of promises allowed to resolve concurrently.

License

The MIT License

Copyright (c) 2015-2016 BusFaster Ltd

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Simple library to limit concurrently running promises

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮