Skip to content

Commit

Permalink
feat(hw): raceWithSignal
Browse files Browse the repository at this point in the history
  • Loading branch information
changshou83 committed Feb 1, 2023
1 parent 6cbdf3d commit a0abd37
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions HandWriting/tools/raceWithSignal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const noop = () => {};

export const raceWithSignal = (signal, promise) => {
let cleanup = noop;
return new Promise((resolve, reject) => {
const notifyRejection = () => reject(new TaskAbortError(signal.reason));

if (signal.aborted) {
notifyRejection();
return;
}

cleanup = addAbortSignalListener(signal, notifyRejection);
promise.finally(() => cleanup()).then(resolve, reject);
}).finally(() => {
cleanup = noop;
});
};

export const addAbortSignalListener = (signal, callback) => {
signal.addEventListener("abort", callback, { once: true });
return () => signal.removeEventListener("abort", callback);
};

0 comments on commit a0abd37

Please sign in to comment.