Skip to content

Commit

Permalink
Fix cleaning up abort listener (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
liuhanqu authored Dec 5, 2024
1 parent a38d5a7 commit 65e893e
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default async function pMap(
signal,
} = {},
) {
return new Promise((resolve, reject_) => {
return new Promise((resolve_, reject_) => {
if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
}
Expand All @@ -30,20 +30,32 @@ export default async function pMap(
let currentIndex = 0;
const iterator = iterable[Symbol.iterator] === undefined ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();

const signalListener = () => {
reject(signal.reason);
};

const cleanup = () => {
signal?.removeEventListener('abort', signalListener);
};

const resolve = value => {
resolve_(value);
cleanup();
};

const reject = reason => {
isRejected = true;
isResolved = true;
reject_(reason);
cleanup();
};

if (signal) {
if (signal.aborted) {
reject(signal.reason);
}

signal.addEventListener('abort', () => {
reject(signal.reason);
});
signal.addEventListener('abort', signalListener, {once: true});
}

const next = async () => {
Expand Down

0 comments on commit 65e893e

Please sign in to comment.