Skip to content

Commit

Permalink
Throw away future values after an error
Browse files Browse the repository at this point in the history
Signed-off-by: Richie Bendall <richiebendall@gmail.com>
  • Loading branch information
Richienb committed Nov 23, 2023
1 parent f3050c0 commit 8422083
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
10 changes: 9 additions & 1 deletion index.js
Expand Up @@ -255,6 +255,7 @@ export function pMapIterable(
isDone = true;
waitingQueue[pendingQueue.length] = {done: true};
tryToFlushWaitingQueue();

return;
}

Expand All @@ -275,9 +276,12 @@ export function pMapIterable(
} catch (error) {
const index = pendingQueue.indexOf(promise);

pendingQueue.splice(index, 1);
pendingQueue.splice(index);

waitingQueue[index] = {error};

isDone = true;
waitingQueue[index + 1] = {done: true};
} finally {
tryToFlushWaitingQueue();
}
Expand All @@ -286,6 +290,10 @@ export function pMapIterable(
pendingQueue.push(promise);
} catch (error) {
waitingQueue[pendingQueue.length] = {error};

isDone = true;
waitingQueue[pendingQueue.length + 1] = {done: true};

tryToFlushWaitingQueue();
}
}
Expand Down
28 changes: 25 additions & 3 deletions test.js
Expand Up @@ -33,6 +33,14 @@ const errorInput2 = [
}, 10],
];

const errorInput3 = [
[20, 10],
[async () => {
throw new Error('bar');
}, 100],
[30, 100],
];

const mapper = async ([value, ms]) => {
await delay(ms);

Expand Down Expand Up @@ -68,9 +76,9 @@ class ThrowingIterator {
index++;
this.index = index;
}
// eslint is wrong - bind is needed else the next() call cannot update
// this.index, which we need to track how many times the iterator was called
// eslint-disable-next-line no-extra-bind
// eslint is wrong - bind is needed else the next() call cannot update
// this.index, which we need to track how many times the iterator was called
// eslint-disable-next-line no-extra-bind
}).bind(this),
};
}
Expand Down Expand Up @@ -532,3 +540,17 @@ test('pMapIterable - mapper that throws', async t => {
throw new Error('foo');
})), {message: 'foo'});
});

test('pMapIterable - stop on error', async t => {
const output = [];

try {
for await (const value of pMapIterable(errorInput3, mapper)) {
output.push(value);
}
} catch (error) {
t.is(error.message, 'bar');
}

t.deepEqual(output, [20]);
});

0 comments on commit 8422083

Please sign in to comment.