├── .editorconfig ├── .gitattributes ├── .github ├── security.md └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export type LimitFunction = { 2 | /** 3 | The number of promises that are currently running. 4 | */ 5 | readonly activeCount: number; 6 | 7 | /** 8 | The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). 9 | */ 10 | readonly pendingCount: number; 11 | 12 | /** 13 | Get or set the concurrency limit. 14 | */ 15 | concurrency: number; 16 | 17 | /** 18 | Discard pending promises that are waiting to run. 19 | 20 | This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. 21 | 22 | Note: This does not cancel promises that are already running. 23 | */ 24 | clearQueue: () => void; 25 | 26 | /** 27 | @param fn - Promise-returning/async function. 28 | @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. 29 | @returns The promise returned by calling `fn(...arguments)`. 30 | */ 31 | ( 32 | function_: (...arguments_: Arguments) => PromiseLike | ReturnType, 33 | ...arguments_: Arguments 34 | ): Promise; 35 | }; 36 | 37 | /** 38 | Run multiple promise-returning & async functions with limited concurrency. 39 | 40 | @param concurrency - Concurrency limit. Minimum: `1`. 41 | @returns A `limit` function. 42 | */ 43 | export default function pLimit(concurrency: number): LimitFunction; 44 | 45 | export type Options = { 46 | /** 47 | Concurrency limit. 48 | 49 | Minimum: `1`. 50 | */ 51 | readonly concurrency: number; 52 | }; 53 | 54 | /** 55 | Returns a function with limited concurrency. 56 | 57 | The returned function manages its own concurrent executions, allowing you to call it multiple times without exceeding the specified concurrency limit. 58 | 59 | Ideal for scenarios where you need to control the number of simultaneous executions of a single function, rather than managing concurrency across multiple functions. 60 | 61 | @param function_ - Promise-returning/async function. 62 | @return Function with limited concurrency. 63 | 64 | @example 65 | ``` 66 | import {limitFunction} from 'p-limit'; 67 | 68 | const limitedFunction = limitFunction(async () => { 69 | return doSomething(); 70 | }, {concurrency: 1}); 71 | 72 | const input = Array.from({length: 10}, limitedFunction); 73 | 74 | // Only one promise is run at once. 75 | await Promise.all(input); 76 | ``` 77 | */ 78 | export function limitFunction( 79 | function_: (...arguments_: Arguments) => PromiseLike | ReturnType, 80 | option: Options 81 | ): (...arguments_: Arguments) => Promise; 82 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import Queue from 'yocto-queue'; 2 | 3 | export default function pLimit(concurrency) { 4 | validateConcurrency(concurrency); 5 | 6 | const queue = new Queue(); 7 | let activeCount = 0; 8 | 9 | const resumeNext = () => { 10 | if (activeCount < concurrency && queue.size > 0) { 11 | queue.dequeue()(); 12 | // Since `pendingCount` has been decreased by one, increase `activeCount` by one. 13 | activeCount++; 14 | } 15 | }; 16 | 17 | const next = () => { 18 | activeCount--; 19 | 20 | resumeNext(); 21 | }; 22 | 23 | const run = async (function_, resolve, arguments_) => { 24 | const result = (async () => function_(...arguments_))(); 25 | 26 | resolve(result); 27 | 28 | try { 29 | await result; 30 | } catch {} 31 | 32 | next(); 33 | }; 34 | 35 | const enqueue = (function_, resolve, arguments_) => { 36 | // Queue `internalResolve` instead of the `run` function 37 | // to preserve asynchronous context. 38 | new Promise(internalResolve => { 39 | queue.enqueue(internalResolve); 40 | }).then( 41 | run.bind(undefined, function_, resolve, arguments_), 42 | ); 43 | 44 | (async () => { 45 | // This function needs to wait until the next microtask before comparing 46 | // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously 47 | // after the `internalResolve` function is dequeued and called. The comparison in the if-statement 48 | // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. 49 | await Promise.resolve(); 50 | 51 | if (activeCount < concurrency) { 52 | resumeNext(); 53 | } 54 | })(); 55 | }; 56 | 57 | const generator = (function_, ...arguments_) => new Promise(resolve => { 58 | enqueue(function_, resolve, arguments_); 59 | }); 60 | 61 | Object.defineProperties(generator, { 62 | activeCount: { 63 | get: () => activeCount, 64 | }, 65 | pendingCount: { 66 | get: () => queue.size, 67 | }, 68 | clearQueue: { 69 | value() { 70 | queue.clear(); 71 | }, 72 | }, 73 | concurrency: { 74 | get: () => concurrency, 75 | 76 | set(newConcurrency) { 77 | validateConcurrency(newConcurrency); 78 | concurrency = newConcurrency; 79 | 80 | queueMicrotask(() => { 81 | // eslint-disable-next-line no-unmodified-loop-condition 82 | while (activeCount < concurrency && queue.size > 0) { 83 | resumeNext(); 84 | } 85 | }); 86 | }, 87 | }, 88 | }); 89 | 90 | return generator; 91 | } 92 | 93 | export function limitFunction(function_, option) { 94 | const {concurrency} = option; 95 | const limit = pLimit(concurrency); 96 | 97 | return (...arguments_) => limit(() => function_(...arguments_)); 98 | } 99 | 100 | function validateConcurrency(concurrency) { 101 | if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { 102 | throw new TypeError('Expected `concurrency` to be a number from 1 and up'); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import pLimit from './index.js'; 3 | 4 | const limit = pLimit(1); 5 | 6 | const input = [ 7 | limit(async () => 'foo'), 8 | limit(async () => 'bar'), 9 | limit(async () => undefined), 10 | ]; 11 | 12 | expectType>>(Promise.all(input)); 13 | 14 | expectType>(limit((_a: string) => '', 'test')); 15 | expectType>(limit(async (_a: string, _b: number) => '', 'test', 1)); 16 | 17 | expectType(limit.activeCount); 18 | expectType(limit.pendingCount); 19 | 20 | expectType(limit.clearQueue()); 21 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "p-limit", 3 | "version": "6.2.0", 4 | "description": "Run multiple promise-returning & async functions with limited concurrency", 5 | "license": "MIT", 6 | "repository": "sindresorhus/p-limit", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "promise", 31 | "limit", 32 | "limited", 33 | "concurrency", 34 | "throttle", 35 | "throat", 36 | "rate", 37 | "batch", 38 | "ratelimit", 39 | "task", 40 | "queue", 41 | "async", 42 | "await", 43 | "promises", 44 | "bluebird" 45 | ], 46 | "dependencies": { 47 | "yocto-queue": "^1.1.1" 48 | }, 49 | "devDependencies": { 50 | "ava": "^6.1.3", 51 | "delay": "^6.0.0", 52 | "in-range": "^3.0.0", 53 | "random-int": "^3.0.0", 54 | "time-span": "^5.1.0", 55 | "tsd": "^0.31.1", 56 | "xo": "^0.58.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # p-limit 2 | 3 | > Run multiple promise-returning & async functions with limited concurrency 4 | 5 | *Works in Node.js and browsers.* 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install p-limit 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```js 16 | import pLimit from 'p-limit'; 17 | 18 | const limit = pLimit(1); 19 | 20 | const input = [ 21 | limit(() => fetchSomething('foo')), 22 | limit(() => fetchSomething('bar')), 23 | limit(() => doSomething()) 24 | ]; 25 | 26 | // Only one promise is run at once 27 | const result = await Promise.all(input); 28 | console.log(result); 29 | ``` 30 | 31 | ## API 32 | 33 | ### pLimit(concurrency) default export 34 | 35 | Returns a `limit` function. 36 | 37 | #### concurrency 38 | 39 | Type: `number`\ 40 | Minimum: `1` 41 | 42 | Concurrency limit. 43 | 44 | ### limit(fn, ...args) 45 | 46 | Returns the promise returned by calling `fn(...args)`. 47 | 48 | #### fn 49 | 50 | Type: `Function` 51 | 52 | Promise-returning/async function. 53 | 54 | #### args 55 | 56 | Any arguments to pass through to `fn`. 57 | 58 | Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. 59 | 60 | ### limit.activeCount 61 | 62 | The number of promises that are currently running. 63 | 64 | ### limit.pendingCount 65 | 66 | The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). 67 | 68 | ### limit.clearQueue() 69 | 70 | Discard pending promises that are waiting to run. 71 | 72 | This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. 73 | 74 | Note: This does not cancel promises that are already running. 75 | 76 | ### limit.concurrency 77 | 78 | Get or set the concurrency limit. 79 | 80 | ### limitFunction(fn, options) named export 81 | 82 | Returns a function with limited concurrency. 83 | 84 | The returned function manages its own concurrent executions, allowing you to call it multiple times without exceeding the specified concurrency limit. 85 | 86 | Ideal for scenarios where you need to control the number of simultaneous executions of a single function, rather than managing concurrency across multiple functions. 87 | 88 | ```js 89 | import {limitFunction} from 'p-limit'; 90 | 91 | const limitedFunction = limitFunction(async () => { 92 | return doSomething(); 93 | }, {concurrency: 1}); 94 | 95 | const input = Array.from({length: 10}, limitedFunction); 96 | 97 | // Only one promise is run at once. 98 | await Promise.all(input); 99 | ``` 100 | 101 | #### fn 102 | 103 | Type: `Function` 104 | 105 | Promise-returning/async function. 106 | 107 | #### options 108 | 109 | Type: `object` 110 | 111 | #### concurrency 112 | 113 | Type: `number`\ 114 | Minimum: `1` 115 | 116 | Concurrency limit. 117 | 118 | ## FAQ 119 | 120 | ### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? 121 | 122 | This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. 123 | 124 | ## Related 125 | 126 | - [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions 127 | - [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions 128 | - [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency 129 | - [More…](https://github.com/sindresorhus/promise-fun) 130 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import {AsyncLocalStorage} from 'node:async_hooks'; 2 | import test from 'ava'; 3 | import delay from 'delay'; 4 | import inRange from 'in-range'; 5 | import timeSpan from 'time-span'; 6 | import randomInt from 'random-int'; 7 | import pLimit, {limitFunction} from './index.js'; 8 | 9 | test('concurrency: 1', async t => { 10 | const input = [ 11 | [10, 300], 12 | [20, 200], 13 | [30, 100], 14 | ]; 15 | 16 | const end = timeSpan(); 17 | const limit = pLimit(1); 18 | 19 | const mapper = ([value, ms]) => limit(async () => { 20 | await delay(ms); 21 | return value; 22 | }); 23 | 24 | t.deepEqual(await Promise.all(input.map(x => mapper(x))), [10, 20, 30]); 25 | t.true(inRange(end(), {start: 590, end: 650})); 26 | }); 27 | 28 | test('concurrency: 4', async t => { 29 | const concurrency = 5; 30 | let running = 0; 31 | 32 | const limit = pLimit(concurrency); 33 | 34 | const input = Array.from({length: 100}, () => limit(async () => { 35 | running++; 36 | t.true(running <= concurrency); 37 | await delay(randomInt(30, 200)); 38 | running--; 39 | })); 40 | 41 | await Promise.all(input); 42 | }); 43 | 44 | test('propagates async execution context properly', async t => { 45 | const concurrency = 2; 46 | const limit = pLimit(concurrency); 47 | const store = new AsyncLocalStorage(); 48 | 49 | const checkId = async id => { 50 | await Promise.resolve(); 51 | t.is(id, store.getStore()?.id); 52 | }; 53 | 54 | const startContext = async id => store.run({id}, () => limit(checkId, id)); 55 | 56 | await Promise.all( 57 | Array.from({length: 100}, (_, id) => startContext(id)), 58 | ); 59 | }); 60 | 61 | test('non-promise returning function', async t => { 62 | await t.notThrowsAsync(async () => { 63 | const limit = pLimit(1); 64 | await limit(() => null); 65 | }); 66 | }); 67 | 68 | test('continues after sync throw', async t => { 69 | const limit = pLimit(1); 70 | let ran = false; 71 | 72 | const promises = [ 73 | limit(() => { 74 | throw new Error('err'); 75 | }), 76 | limit(() => { 77 | ran = true; 78 | }), 79 | ]; 80 | 81 | await Promise.all(promises).catch(() => {}); 82 | 83 | t.is(ran, true); 84 | }); 85 | 86 | test('accepts additional arguments', async t => { 87 | const limit = pLimit(1); 88 | const symbol = Symbol('test'); 89 | 90 | await limit(a => t.is(a, symbol), symbol); 91 | }); 92 | 93 | test('does not ignore errors', async t => { 94 | const limit = pLimit(1); 95 | const error = new Error('🦄'); 96 | 97 | const promises = [ 98 | limit(async () => { 99 | await delay(30); 100 | }), 101 | limit(async () => { 102 | await delay(80); 103 | throw error; 104 | }), 105 | limit(async () => { 106 | await delay(50); 107 | }), 108 | ]; 109 | 110 | await t.throwsAsync(Promise.all(promises), {is: error}); 111 | }); 112 | 113 | test('activeCount and pendingCount properties', async t => { 114 | const limit = pLimit(5); 115 | t.is(limit.activeCount, 0); 116 | t.is(limit.pendingCount, 0); 117 | 118 | const runningPromise1 = limit(() => delay(1000)); 119 | t.is(limit.activeCount, 0); 120 | t.is(limit.pendingCount, 1); 121 | 122 | await Promise.resolve(); 123 | t.is(limit.activeCount, 1); 124 | t.is(limit.pendingCount, 0); 125 | 126 | await runningPromise1; 127 | t.is(limit.activeCount, 0); 128 | t.is(limit.pendingCount, 0); 129 | 130 | const immediatePromises = Array.from({length: 5}, () => limit(() => delay(1000))); 131 | const delayedPromises = Array.from({length: 3}, () => limit(() => delay(1000))); 132 | 133 | await Promise.resolve(); 134 | t.is(limit.activeCount, 5); 135 | t.is(limit.pendingCount, 3); 136 | 137 | await Promise.all(immediatePromises); 138 | t.is(limit.activeCount, 3); 139 | t.is(limit.pendingCount, 0); 140 | 141 | await Promise.all(delayedPromises); 142 | 143 | t.is(limit.activeCount, 0); 144 | t.is(limit.pendingCount, 0); 145 | }); 146 | 147 | test('clearQueue', async t => { 148 | const limit = pLimit(1); 149 | 150 | Array.from({length: 1}, () => limit(() => delay(1000))); 151 | Array.from({length: 3}, () => limit(() => delay(1000))); 152 | 153 | await Promise.resolve(); 154 | t.is(limit.pendingCount, 3); 155 | limit.clearQueue(); 156 | t.is(limit.pendingCount, 0); 157 | }); 158 | 159 | test('throws on invalid concurrency argument', t => { 160 | t.throws(() => { 161 | pLimit(0); 162 | }); 163 | 164 | t.throws(() => { 165 | pLimit(-1); 166 | }); 167 | 168 | t.throws(() => { 169 | pLimit(1.2); 170 | }); 171 | 172 | t.throws(() => { 173 | pLimit(undefined); 174 | }); 175 | 176 | t.throws(() => { 177 | pLimit(true); 178 | }); 179 | }); 180 | 181 | test('change concurrency to smaller value', async t => { 182 | const limit = pLimit(4); 183 | let running = 0; 184 | const log = []; 185 | const promises = Array.from({length: 10}).map(() => 186 | limit(async () => { 187 | ++running; 188 | log.push(running); 189 | await delay(50); 190 | --running; 191 | }), 192 | ); 193 | await delay(0); 194 | t.is(running, 4); 195 | 196 | limit.concurrency = 2; 197 | await Promise.all(promises); 198 | t.deepEqual(log, [1, 2, 3, 4, 2, 2, 2, 2, 2, 2]); 199 | }); 200 | 201 | test('change concurrency to bigger value', async t => { 202 | const limit = pLimit(2); 203 | let running = 0; 204 | const log = []; 205 | const promises = Array.from({length: 10}).map(() => 206 | limit(async () => { 207 | ++running; 208 | log.push(running); 209 | await delay(50); 210 | --running; 211 | }), 212 | ); 213 | await delay(0); 214 | t.is(running, 2); 215 | 216 | limit.concurrency = 4; 217 | await Promise.all(promises); 218 | t.deepEqual(log, [1, 2, 3, 4, 4, 4, 4, 4, 4, 4]); 219 | }); 220 | 221 | test('limitFunction()', async t => { 222 | const concurrency = 5; 223 | let running = 0; 224 | 225 | const limitedFunction = limitFunction(async () => { 226 | running++; 227 | t.true(running <= concurrency); 228 | await delay(randomInt(30, 200)); 229 | running--; 230 | }, {concurrency}); 231 | 232 | const input = Array.from({length: 100}, limitedFunction); 233 | 234 | await Promise.all(input); 235 | }); 236 | --------------------------------------------------------------------------------