Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix concurrency control in pMapIterable #77

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,31 +191,31 @@ export function pMapIterable(
const iterator = iterable[Symbol.asyncIterator] === undefined ? iterable[Symbol.iterator]() : iterable[Symbol.asyncIterator]();

const promises = [];
let runningMappersCount = 0;
let pendingPromisesCount = 0;
let isDone = false;
let index = 0;

function trySpawn() {
if (isDone || !(runningMappersCount < concurrency && promises.length < backpressure)) {
if (isDone || !(pendingPromisesCount < concurrency && promises.length < backpressure)) {
return;
}

const promise = (async () => {
pendingPromisesCount++;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we could be even more explicit by moving this up an additional level?

const {done, value} = await iterator.next();

if (done) {
pendingPromisesCount--;
return {done: true};
}

runningMappersCount++;

// Spawn if still below concurrency and backpressure limit
trySpawn();

try {
const returnValue = await mapper(await value, index++);

runningMappersCount--;
pendingPromisesCount--;

if (returnValue === pMapSkip) {
const index = promises.indexOf(promise);
Expand Down
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,23 @@ test('pMapIterable - backpressure', async t => {
t.is(currentValue, 40);
});

test('pMapIterable - async input, backpressure > concurrency', async t => {
async function * source() {
yield 1;
yield 2;
yield 3;
}

const log = [];
await collectAsyncIterable(pMapIterable(source(), async n => {
log.push(n);
await delay(100);
log.push(n);
}, {concurrency: 1, backpressure: 2}));

t.deepEqual(log, [1, 1, 2, 2, 3, 3]);
});

test('pMapIterable - pMapSkip', async t => {
t.deepEqual(await collectAsyncIterable(pMapIterable([
1,
Expand Down