Skip to content
/ cwait Public

⌛ Limit number of promises running in parallel

License

Notifications You must be signed in to change notification settings

charto/cwait

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cwait

build status npm version

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

Docs generated using docts

Class Task

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

Methods:

new( ) Task
 ▪ func () => PromiseType
.delay( ) PromiseType
Wrap task result in a new promise so it can be resolved later.
 ▪ Promise PromisyClass
.resume( ) PromiseType
Start the 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