Skip to content

Commit

Permalink
[core-util] Edit delay() (#24801)
Browse files Browse the repository at this point in the history
Minor edit to use modern syntax and simpler control flow.
  • Loading branch information
deyaaeldeen authored Feb 9, 2023
1 parent 73fa703 commit 00350a6
Showing 1 changed file with 15 additions and 29 deletions.
44 changes: 15 additions & 29 deletions sdk/core/core-util/src/delay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
// Licensed under the MIT license.

import { AbortError, AbortSignalLike } from "@azure/abort-controller";
import { isDefined } from "./typeGuards";

const StandardAbortMessage = "The operation was aborted.";
const StandardAbortMessage = "The delay was aborted.";

/**
* Options for support abort functionality for the delay method
Expand All @@ -28,38 +27,25 @@ export interface DelayOptions {
*/
export function delay(timeInMs: number, options?: DelayOptions): Promise<void> {
return new Promise((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined = undefined;
let onAborted: (() => void) | undefined = undefined;

const rejectOnAbort = (): void => {
return reject(new AbortError(options?.abortErrorMsg ?? StandardAbortMessage));
};

const removeListeners = (): void => {
if (options?.abortSignal && onAborted) {
options.abortSignal.removeEventListener("abort", onAborted);
}
};

onAborted = (): void => {
if (isDefined(timer)) {
clearTimeout(timer);
}
function rejectOnAbort(): void {
reject(new AbortError(options?.abortErrorMsg ?? StandardAbortMessage));
}
function removeListeners(): void {
options?.abortSignal?.removeEventListener("abort", onAbort);
}
function onAbort(): void {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(token);
removeListeners();
return rejectOnAbort();
};

if (options?.abortSignal && options.abortSignal.aborted) {
rejectOnAbort();
}
if (options?.abortSignal?.aborted) {
return rejectOnAbort();
}

timer = setTimeout(() => {
const token = setTimeout(() => {
removeListeners();
resolve();
}, timeInMs);

if (options?.abortSignal) {
options.abortSignal.addEventListener("abort", onAborted);
}
options?.abortSignal?.addEventListener("abort", onAbort);
});
}

0 comments on commit 00350a6

Please sign in to comment.