├── .gitattributes ├── .prettierignore ├── .gitignore ├── eslint.config.js ├── pnpm-workspace.yaml ├── vitest.setup.ts ├── vitest.config.ts ├── src ├── index.bench.ts ├── index.ts └── index.test.ts ├── types └── jest-extended.d.ts ├── notice-apache ├── tsdown.config.ts ├── tsconfig.json ├── license-mit ├── .github └── workflows │ └── ci.yml ├── package.json ├── readme.md └── license-apache /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | pnpm-lock.yaml 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /coverage/ 3 | /dist/ 4 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | export { default } from '@tomer/eslint-config' 2 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | shellEmulator: true 2 | onlyBuiltDependencies: 3 | - esbuild 4 | - unrs-resolver 5 | -------------------------------------------------------------------------------- /vitest.setup.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'vitest' 2 | import * as matchers from 'jest-extended' 3 | 4 | expect.extend(matchers) 5 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | export default defineConfig({ 4 | test: { 5 | environment: `jsdom`, 6 | setupFiles: [`vitest.setup.ts`], 7 | coverage: { 8 | include: [`src`], 9 | }, 10 | }, 11 | }) 12 | -------------------------------------------------------------------------------- /src/index.bench.ts: -------------------------------------------------------------------------------- 1 | import { setTimeout } from 'node:timers/promises' 2 | import { bench } from 'vitest' 3 | import limitConcur from './index.ts' 4 | 5 | bench(`limitConcur`, async () => { 6 | const limited = limitConcur(4, () => setTimeout(20)) 7 | 8 | await Promise.all(Array.from({ length: 12 }, () => limited())) 9 | }) 10 | -------------------------------------------------------------------------------- /types/jest-extended.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable typescript/no-empty-object-type */ 2 | /* eslint-disable typescript/consistent-type-definitions */ 3 | import type CustomMatchers from 'jest-extended' 4 | import 'vitest' 5 | 6 | declare module 'vitest' { 7 | interface Assertion extends CustomMatchers {} 8 | interface AsymmetricMatchersContaining extends CustomMatchers {} 9 | interface ExpectStatic extends CustomMatchers {} 10 | } 11 | -------------------------------------------------------------------------------- /notice-apache: -------------------------------------------------------------------------------- 1 | Copyright 2021-2024 Google LLC 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /tsdown.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsdown/config' 2 | import treeShakeable from 'rollup-plugin-tree-shakeable' 3 | import terser from '@rollup/plugin-terser' 4 | 5 | export default defineConfig([ 6 | { 7 | entry: `src/index.ts`, 8 | platform: `neutral`, 9 | sourcemap: `inline`, 10 | publint: true, 11 | plugins: [ 12 | terser({ 13 | mangle: { 14 | properties: { 15 | regex: `^_[^_]+`, 16 | }, 17 | }, 18 | }), 19 | treeShakeable(), 20 | ], 21 | }, 22 | { 23 | entry: `src/index.ts`, 24 | dts: { emitDtsOnly: true }, 25 | }, 26 | ]) 27 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | // Base options 4 | "esModuleInterop": true, 5 | "skipLibCheck": true, 6 | "target": "esnext", 7 | "allowJs": true, 8 | "resolveJsonModule": true, 9 | "moduleDetection": "force", 10 | "isolatedModules": true, 11 | "verbatimModuleSyntax": true, 12 | "incremental": true, 13 | "tsBuildInfoFile": "node_modules/.cache/tsconfig.tsbuildinfo", 14 | // Strictness 15 | "strict": true, 16 | "noUncheckedIndexedAccess": true, 17 | "noImplicitOverride": true, 18 | "noImplicitReturns": true, 19 | // Using a bundler 20 | "allowImportingTsExtensions": true, 21 | "module": "preserve", 22 | "moduleResolution": "bundler", 23 | "noEmit": true, 24 | // Runtime 25 | "lib": ["esnext"] 26 | }, 27 | "include": ["**/*"] 28 | } 29 | -------------------------------------------------------------------------------- /license-mit: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024-2025 Tomer Aberbach 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.ref }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | test: 15 | name: Node.js v${{ matrix.nodejs }} (${{ matrix.os }}) 16 | timeout-minutes: 5 17 | runs-on: ${{ matrix.os }} 18 | strategy: 19 | matrix: 20 | nodejs: [22, 24] 21 | os: [ubuntu-latest, macOS-latest] 22 | fail-fast: false 23 | steps: 24 | - uses: actions/checkout@v4 25 | 26 | - name: Install Node.js 27 | uses: actions/setup-node@v4 28 | with: 29 | node-version: ${{ matrix.nodejs }} 30 | 31 | - name: Install pnpm 32 | run: npm install -g pnpm 33 | 34 | - name: Install dependencies 35 | run: pnpm install 36 | 37 | - name: Build 38 | run: pnpm build 39 | 40 | - name: Lint 41 | run: pnpm lint --no-fix 42 | 43 | - name: Format 44 | run: pnpm format --no-write --check 45 | 46 | - name: Typecheck 47 | run: pnpm typecheck 48 | 49 | - name: Test 50 | run: pnpm coverage 51 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | const wrapFunction = any>( 2 | from: (...args: any[]) => any, 3 | to: Fn, 4 | ): Fn => 5 | Object.defineProperties(to, { 6 | length: { value: from.length }, 7 | name: { value: from.name }, 8 | }) 9 | 10 | const noop = () => {} 11 | 12 | /** 13 | * Return a function equivalent to {@link fn} except that at most 14 | * {@link concurrency} calls to {@link fn} can run at once at any given time. 15 | */ 16 | const limitConcur = Promise>( 17 | concurrency: number, 18 | fn: Fn, 19 | ): Fn => { 20 | if (!Number.isSafeInteger(concurrency) || concurrency <= 0) { 21 | throw new TypeError( 22 | `Expected \`concurrency\` to be a positive integer: ${concurrency}`, 23 | ) 24 | } 25 | 26 | const pending = new Set() 27 | 28 | return wrapFunction(fn, (async (...args) => { 29 | while (pending.size === concurrency) { 30 | await Promise.race(pending) 31 | } 32 | 33 | // eslint-disable-next-line typescript/no-unsafe-argument 34 | const promise = fn(...args) 35 | 36 | void (async () => { 37 | const nonThrowingPromise = promise.then(noop).catch(noop) 38 | pending.add(nonThrowingPromise) 39 | await nonThrowingPromise 40 | pending.delete(nonThrowingPromise) 41 | })() 42 | 43 | // eslint-disable-next-line typescript/no-unsafe-return 44 | return promise 45 | }) as Fn) 46 | } 47 | 48 | export default limitConcur 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "limit-concur", 3 | "version": "4.0.0", 4 | "author": { 5 | "name": "Tomer Aberbach", 6 | "email": "tomer@aberba.ch", 7 | "url": "https://tomeraberba.ch" 8 | }, 9 | "description": "Limit an async function's concurrency with ease!", 10 | "keywords": [ 11 | "async", 12 | "concurrency", 13 | "limit", 14 | "limited", 15 | "promise", 16 | "await", 17 | "ratelimit", 18 | "throttle", 19 | "rate" 20 | ], 21 | "homepage": "https://github.com/TomerAberbach/limit-concur", 22 | "repository": "TomerAberbach/limit-concur", 23 | "bugs": { 24 | "url": "https://github.com/TomerAberbach/limit-concur/issues" 25 | }, 26 | "funding": { 27 | "url": "https://github.com/sponsors/TomerAberbach" 28 | }, 29 | "license": "Apache-2.0 AND MIT", 30 | "files": [ 31 | "dist", 32 | "license-apache", 33 | "license-mit", 34 | "notice-apache" 35 | ], 36 | "type": "module", 37 | "sideEffects": false, 38 | "engines": { 39 | "node": ">= 22" 40 | }, 41 | "exports": { 42 | ".": { 43 | "types": "./dist/index.d.ts", 44 | "default": "./dist/index.js" 45 | }, 46 | "./package.json": "./package.json" 47 | }, 48 | "scripts": { 49 | "format": "prettier --cache --write .", 50 | "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ --fix .", 51 | "typecheck": "tsc --noEmit", 52 | "test": "vitest", 53 | "coverage": "vitest --coverage", 54 | "bench": "vitest bench", 55 | "build": "tsdown", 56 | "prepublishOnly": "pnpm build" 57 | }, 58 | "prettier": "@tomer/prettier-config", 59 | "devDependencies": { 60 | "@fast-check/vitest": "^0.2.2", 61 | "@rollup/plugin-terser": "^0.4.4", 62 | "@tomer/eslint-config": "^4.1.0", 63 | "@tomer/prettier-config": "^4.0.0", 64 | "@vitest/coverage-v8": "^3.2.4", 65 | "eslint": "^9.32.0", 66 | "jest-extended": "^6.0.0", 67 | "jsdom": "^26.1.0", 68 | "prettier": "^3.6.2", 69 | "publint": "^0.3.12", 70 | "rollup-plugin-tree-shakeable": "^1.0.3", 71 | "tsdown": "^0.13.2", 72 | "typescript": "^5.9.2", 73 | "vitest": "^3.2.4" 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 | limit-concur 3 |

4 | 5 | 22 | 23 |
24 | Limit an async function's concurrency with ease! 25 |
26 | 27 | ## Features 28 | 29 | - **Tiny:** only ~300 B minzipped 30 | - **Flexible:** works for any function that returns a `Promise` 31 | 32 | ## Install 33 | 34 | ```sh 35 | $ npm i limit-concur 36 | ``` 37 | 38 | ## Usage 39 | 40 | ```js 41 | import limitConcur from 'limit-concur' 42 | 43 | const categories = await ( 44 | await fetch(`https://api.chucknorris.io/jokes/categories`) 45 | ).json() 46 | 47 | let pendingRequests = 0 48 | const getChuckNorrisJoke = async category => { 49 | console.log(`pending requests: ${++pendingRequests}`) 50 | const response = await fetch( 51 | `https://api.chucknorris.io/jokes/random?category=${encodeURIComponent(category)}`, 52 | ) 53 | const { value } = await response.json() 54 | console.log(`pending requests: ${--pendingRequests}`) 55 | return value 56 | } 57 | 58 | const limitedGetChuckNorrisJoke = limitConcur(4, getChuckNorrisJoke) 59 | 60 | // At most 4 requests are pending at any given time! 61 | const jokes = await Promise.all(categories.map(limitedGetChuckNorrisJoke)) 62 | console.log(jokes) 63 | //=> pending requests: 1 64 | //=> pending requests: 2 65 | //=> pending requests: 3 66 | //=> pending requests: 4 67 | //=> pending requests: 3 68 | //=> pending requests: 4 69 | //=> ... 70 | //=> pending requests: 3 71 | //=> pending requests: 2 72 | //=> pending requests: 1 73 | //=> pending requests: 0 74 | //=> [ 75 | // 'Chuck Norris once rode a nine foot grizzly bear through an automatic car wash, instead of taking a shower.', 76 | // "Chuck Norris is actually the front man for Apple. He let's Steve Jobs run the show when he's on a mission. Chuck Norris is always on a mission.", 77 | // "Bill Gates thinks he's Chuck Norris. Chuck Norris actually laughed. Once.", 78 | // 'Chuck Norris can install iTunes without installing Quicktime.', 79 | // ... 80 | // ] 81 | ``` 82 | 83 | ### Recipes 84 | 85 | #### Replacing [`p-map`](https://github.com/sindresorhus/p-map) 86 | 87 | ```js 88 | import limitConcur from 'limit-concur' 89 | 90 | const urls = [`https://tomeraberba.ch`, `https://lfi.dev`, `https://npmjs.com`] 91 | 92 | const mapper = async url => { 93 | const { redirected } = await fetch(url, { method: `head` }) 94 | return redirected 95 | } 96 | 97 | const results = await Promise.all(urls.map(limitConcur(2, mapper))) 98 | console.log(results) 99 | //=> [ false, false, true ] 100 | ``` 101 | 102 | #### Replacing [`p-all`](https://github.com/sindresorhus/p-all) 103 | 104 | ```js 105 | import limitConcur from 'limit-concur' 106 | 107 | const actions = [ 108 | () => fetch(`https://tomeraberba.ch`), 109 | () => fetch(`https://lfi.dev`), 110 | () => checkSomething(), 111 | () => doSomethingElse(), 112 | ] 113 | 114 | const results = await Promise.all( 115 | actions.map(limitConcur(2, action => action())), 116 | ) 117 | console.log(results) 118 | //=> [ ..., ..., ... ] 119 | ``` 120 | 121 | #### Replacing [`p-limit`](https://github.com/sindresorhus/p-limit) 122 | 123 | ```js 124 | import limitConcur from 'limit-concur' 125 | 126 | const limit = limitConcur(1, fn => fn()) 127 | 128 | const input = [ 129 | limit(() => fetchSomething(`foo`)), 130 | limit(() => fetchSomething(`bar`)), 131 | limit(() => doSomething()), 132 | ] 133 | 134 | const results = await Promise.all(input) 135 | console.log(results) 136 | //=> [ ..., ..., ... ] 137 | ``` 138 | 139 | #### Replacing [`p-filter`](https://github.com/sindresorhus/p-filter) 140 | 141 | ```js 142 | import limitConcur from 'limit-concur' 143 | 144 | const urls = [`https://tomeraberba.ch`, `https://lfi.dev`, `https://npmjs.com`] 145 | 146 | const filterer = async url => { 147 | const { redirected } = await fetch(url, { method: `head` }) 148 | return !redirected 149 | } 150 | 151 | const results = await Promise.all( 152 | urls.map(limitConcur(2, async url => ({ url, keep: await filterer(url) }))), 153 | ) 154 | const filtered = results.flatMap(({ url, keep }) => (keep ? [url] : [])) 155 | console.log(filtered) 156 | //=> [ 'https://tomeraberba.ch', 'https://lfi.dev' ] 157 | ``` 158 | 159 | #### Replacing [`p-props`](https://github.com/sindresorhus/p-props) 160 | 161 | ```js 162 | import limitConcur from 'limit-concur' 163 | 164 | const urls = { 165 | tomer: `https://tomeraberba.ch`, 166 | lfi: `https://lfi.dev`, 167 | npm: `https://npmjs.com`, 168 | } 169 | 170 | const mapper = async url => { 171 | const { redirected } = await fetch(url, { method: `head` }) 172 | return redirected 173 | } 174 | 175 | const results = Object.fromEntries( 176 | await Promise.all( 177 | Object.entries(urls).map( 178 | limitConcur(2, async ([name, url]) => [name, await mapper(url)]), 179 | ), 180 | ), 181 | ) 182 | console.log(results) 183 | //=> { tomer: false, lfi: false, npm: true } 184 | ``` 185 | 186 | ## Contributing 187 | 188 | Stars are always welcome! 189 | 190 | For bugs and feature requests, 191 | [please create an issue](https://github.com/TomerAberbach/limit-concur/issues/new). 192 | 193 | ## License 194 | 195 | [MIT](https://github.com/TomerAberbach/limit-concur/blob/main/license-mit) © 196 | [Tomer Aberbach](https://github.com/TomerAberbach) \ 197 | [Apache 2.0](https://github.com/TomerAberbach/limit-concur/blob/main/license-apache) © 198 | [Google](https://github.com/TomerAberbach/limit-concur/blob/main/notice-apache) 199 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { inspect } from 'node:util' 2 | import { fc, test } from '@fast-check/vitest' 3 | import { afterEach, beforeEach, expect, vi } from 'vitest' 4 | import limitConcur from './index.ts' 5 | 6 | beforeEach(() => { 7 | vi.useFakeTimers() 8 | }) 9 | afterEach(() => { 10 | vi.restoreAllMocks() 11 | }) 12 | 13 | // NOTE: We don't use `setTimeout` from `node:timers/promises` because 14 | // `useFakeTimers()` doesn't affect it. 15 | const delay = (ms: number) => 16 | new Promise(resolve => { 17 | setTimeout(resolve, ms) 18 | }) 19 | 20 | const promiseStateSync = ( 21 | promise: Promise, 22 | ): `pending` | `rejected` | `fulfilled` => { 23 | const inspectedString = inspect(promise, { 24 | depth: 0, 25 | showProxy: false, 26 | maxStringLength: 0, 27 | breakLength: Number.POSITIVE_INFINITY, 28 | }) 29 | 30 | if (inspectedString.startsWith(`Promise { `)) { 31 | return `pending` 32 | } 33 | 34 | if (inspectedString.startsWith(`Promise { `)) { 35 | return `rejected` 36 | } 37 | 38 | return `fulfilled` 39 | } 40 | 41 | const withAutoAdvancingTimers = 42 | ( 43 | fn: (...args: Args) => Promise, 44 | ): ((...args: Args) => Promise) => 45 | async (...args) => { 46 | const promise = fn(...args) 47 | while (vi.getTimerCount() > 0) { 48 | await vi.runAllTimersAsync() 49 | } 50 | await promise 51 | } 52 | 53 | const asyncFnArb = fc 54 | .tuple( 55 | fc.infiniteStream(fc.integer({ min: 1, max: 50 }).map(i => i * 1000)), 56 | fc.func(fc.anything()), 57 | ) 58 | .map(([delays, fn]) => 59 | Object.assign( 60 | async (...args: unknown[]) => { 61 | await delay(Number(delays.next().value)) 62 | return fn(...args) 63 | }, 64 | { 65 | toString: () => 66 | `(...args) => delay().then(() => (${fc.stringify(fn)})(...args))`, 67 | }, 68 | ), 69 | ) 70 | 71 | const maybeThrowingAsyncFnArb = fc 72 | .tuple(fc.func(fc.boolean()), asyncFnArb) 73 | .map(([shouldThrow, asyncFn]) => 74 | Object.assign( 75 | async (...args: unknown[]) => { 76 | const output = await asyncFn(...args) 77 | 78 | if (shouldThrow(...args)) { 79 | throw new Error(`BOOM!`) 80 | } 81 | 82 | return output 83 | }, 84 | { 85 | toString: () => 86 | `(...args) => maybeThrow().then(() => (${fc.stringify( 87 | asyncFn, 88 | )})(...args))`, 89 | shouldThrow, 90 | }, 91 | ), 92 | ) 93 | 94 | test.prop([ 95 | fc.oneof(fc.double({ noInteger: true }), fc.integer({ max: 0 })), 96 | asyncFnArb, 97 | ])( 98 | `limitConcur throws for a non positive integer concurrency`, 99 | (concurrency, fn) => { 100 | expect(() => limitConcur(concurrency, fn)).toThrow( 101 | new TypeError( 102 | `Expected \`concurrency\` to be a positive integer: ${concurrency}`, 103 | ), 104 | ) 105 | }, 106 | ) 107 | 108 | test.prop([ 109 | fc.integer({ min: 1 }), 110 | asyncFnArb, 111 | fc.array(fc.array(fc.anything()), { minLength: 1 }), 112 | ])( 113 | `limitConcur limits the given function's concurrency`, 114 | withAutoAdvancingTimers(async (concurrency, fn, inputs) => { 115 | let running = 0 116 | 117 | const limitedFn = limitConcur(concurrency, async (...args: unknown[]) => { 118 | running++ 119 | 120 | expect(running).toBeLessThanOrEqual(concurrency) 121 | 122 | const output = await fn(...args) 123 | 124 | running-- 125 | 126 | return output 127 | }) 128 | 129 | const outputs = await Promise.all(inputs.map(input => limitedFn(...input))) 130 | 131 | expect(await Promise.all(inputs.map(input => fn(...input)))).toStrictEqual( 132 | outputs, 133 | ) 134 | }), 135 | ) 136 | 137 | test.prop([ 138 | fc.integer({ min: 1 }), 139 | maybeThrowingAsyncFnArb, 140 | fc.array(fc.array(fc.anything()), { minLength: 1 }), 141 | ])( 142 | `limitConcur limits the given function's concurrency when errors are thrown`, 143 | withAutoAdvancingTimers(async (concurrency, fn, inputs) => { 144 | let running = 0 145 | 146 | const limitedFn = limitConcur(concurrency, async (...args: unknown[]) => { 147 | running++ 148 | 149 | expect(running).toBeLessThanOrEqual(concurrency) 150 | 151 | try { 152 | return await fn(...args) 153 | } finally { 154 | running-- 155 | } 156 | }) 157 | 158 | const outputs = inputs.map(input => ({ 159 | shouldThrow: fn.shouldThrow(...input), 160 | didThrow: (async () => { 161 | try { 162 | await limitedFn(...input) 163 | return false 164 | } catch { 165 | return true 166 | } 167 | })(), 168 | })) 169 | 170 | for (const { shouldThrow, didThrow } of outputs) { 171 | expect(await didThrow).toBe(shouldThrow) 172 | } 173 | }), 174 | ) 175 | 176 | test( 177 | `limitConcur concrete example`, 178 | withAutoAdvancingTimers(async () => { 179 | let running = 0 180 | const limitedDelay = limitConcur(3, async (timeout: number) => { 181 | running++ 182 | await delay(timeout) 183 | running-- 184 | }) 185 | 186 | // Queued: {} 187 | // Pending: { first: 4000 } 188 | // Done: {} 189 | const first = limitedDelay(4000) 190 | 191 | expect(promiseStateSync(first)).toBe(`pending`) 192 | expect(running).toBe(1) 193 | 194 | // Queued: {} 195 | // Pending: { first: 3000 } 196 | // Done: {} 197 | await delay(1000) 198 | 199 | expect(promiseStateSync(first)).toBe(`pending`) 200 | expect(running).toBe(1) 201 | 202 | // Queued: {} 203 | // Pending: { first: 3000, second: 2000 } 204 | // Done: {} 205 | const second = limitedDelay(2000) 206 | 207 | expect(promiseStateSync(first)).toBe(`pending`) 208 | expect(promiseStateSync(second)).toBe(`pending`) 209 | expect(running).toBe(2) 210 | 211 | // Queued: {} 212 | // Pending: { first: 3000, second: 2000, third: 5000 } 213 | // Done: {} 214 | const third = limitedDelay(5000) 215 | 216 | expect(promiseStateSync(first)).toBe(`pending`) 217 | expect(promiseStateSync(second)).toBe(`pending`) 218 | expect(promiseStateSync(third)).toBe(`pending`) 219 | expect(running).toBe(3) 220 | 221 | // Queued: { fourth: 5000 } 222 | // Pending: { first: 3000, second: 2000, third: 5000 } 223 | // Done: {} 224 | const fourth = limitedDelay(5000) 225 | 226 | expect(promiseStateSync(first)).toBe(`pending`) 227 | expect(promiseStateSync(second)).toBe(`pending`) 228 | expect(promiseStateSync(third)).toBe(`pending`) 229 | expect(promiseStateSync(fourth)).toBe(`pending`) 230 | expect(running).toBe(3) 231 | 232 | // Queued: {} 233 | // Pending: { first: 1000, third: 3000, fourth: 5000 } 234 | // Done: { second: 0 } 235 | await delay(2000) 236 | 237 | expect(promiseStateSync(first)).toBe(`pending`) 238 | expect(promiseStateSync(second)).toBe(`fulfilled`) 239 | expect(promiseStateSync(third)).toBe(`pending`) 240 | expect(promiseStateSync(fourth)).toBe(`pending`) 241 | expect(running).toBe(3) 242 | 243 | // Queued: {} 244 | // Pending: { third: 1000, fourth: 3000 } 245 | // Done: { first: 0, second: 0 } 246 | await delay(2000) 247 | 248 | expect(promiseStateSync(first)).toBe(`fulfilled`) 249 | expect(promiseStateSync(second)).toBe(`fulfilled`) 250 | expect(promiseStateSync(third)).toBe(`pending`) 251 | expect(promiseStateSync(fourth)).toBe(`pending`) 252 | expect(running).toBe(2) 253 | 254 | // Queued: {} 255 | // Pending: { fourth: 2000 } 256 | // Done: { first: 0, second: 0, third: 0 } 257 | await delay(1000) 258 | 259 | expect(promiseStateSync(first)).toBe(`fulfilled`) 260 | expect(promiseStateSync(second)).toBe(`fulfilled`) 261 | expect(promiseStateSync(third)).toBe(`fulfilled`) 262 | expect(promiseStateSync(fourth)).toBe(`pending`) 263 | expect(running).toBe(1) 264 | 265 | // Queued: {} 266 | // Pending: { fourth: 1000 } 267 | // Done: { first: 0, second: 0, third: 0 } 268 | await delay(1000) 269 | 270 | expect(promiseStateSync(first)).toBe(`fulfilled`) 271 | expect(promiseStateSync(second)).toBe(`fulfilled`) 272 | expect(promiseStateSync(third)).toBe(`fulfilled`) 273 | expect(promiseStateSync(fourth)).toBe(`pending`) 274 | expect(running).toBe(1) 275 | 276 | // Queued: {} 277 | // Pending: {} 278 | // Done: { first: 0, second: 0, third: 0, fourth: 0 } 279 | await delay(1000) 280 | 281 | expect(promiseStateSync(first)).toBe(`fulfilled`) 282 | expect(promiseStateSync(second)).toBe(`fulfilled`) 283 | expect(promiseStateSync(third)).toBe(`fulfilled`) 284 | expect(promiseStateSync(fourth)).toBe(`fulfilled`) 285 | expect(running).toBe(0) 286 | }), 287 | ) 288 | -------------------------------------------------------------------------------- /license-apache: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. --------------------------------------------------------------------------------