From 82c43ba2e37fb6e7f62ccd9bec8c5f48575f0613 Mon Sep 17 00:00:00 2001 From: undergroundwires Date: Sat, 30 Oct 2021 12:35:20 +0100 Subject: [PATCH] Refactor to remove "Async" function name suffix Remove convention where Async suffix is added to functions that returns a Promise. It was a habit from C#, but is not widely used in JavaScript / TypeScript world, also bloats the code. The code is more consistent with third party dependencies/frameworks without the suffix. --- src/application/ApplicationFactory.ts | 4 +- .../Context/ApplicationContextFactory.ts | 4 +- src/application/IApplicationFactory.ts | 2 +- src/infrastructure/CodeRunner.ts | 2 +- src/infrastructure/Threading/AsyncLazy.ts | 2 +- src/infrastructure/Threading/AsyncSleep.ts | 2 +- .../Code/CodeButtons/MacOsInstructions.vue | 2 +- .../Code/CodeButtons/TheCodeButtons.vue | 28 +++++----- .../components/Code/TheCodeArea.vue | 6 +-- .../components/Scripts/Menu/TheOsChanger.vue | 8 +-- .../Scripts/View/Cards/CardListItem.vue | 18 +++---- .../Scripts/View/ScriptsTree/ScriptsTree.vue | 10 ++-- .../SelectableTree/Node/RevertToggle.vue | 10 ++-- .../SelectableTree/SelectableTree.vue | 22 ++++---- .../Scripts/View/TheScriptsView.vue | 8 +-- .../components/Shared/StatefulVue.ts | 10 ++-- .../TheFooter/DownloadUrlListItem.vue | 10 ++-- .../components/TheFooter/PrivacyPolicy.vue | 2 +- .../components/TheFooter/TheFooter.vue | 2 +- src/presentation/components/TheHeader.vue | 2 +- src/presentation/components/TheSearchBar.vue | 4 +- .../electron/Update/AutoUpdater.ts | 14 ++--- .../electron/Update/ManualUpdater.ts | 18 +++---- src/presentation/electron/Update/Updater.ts | 16 +++--- src/presentation/electron/main.ts | 2 +- .../NoDeadDocumentationUrls.spec.ts | 4 +- .../StatusChecker/BatchStatusChecker.ts | 20 +++---- .../ExponentialBackOffRetryHandler.ts | 8 +-- .../collections/StatusChecker/README.md | 10 ++-- .../collections/StatusChecker/Requestor.ts | 6 +-- .../application/ApplicationFactory.spec.ts | 18 +++---- .../Context/ApplicationContextFactory.spec.ts | 14 ++--- tests/unit/infrastructure/CodeRunner.spec.ts | 16 +++--- .../Threading/AsyncLazy.spec.ts | 18 +++---- .../Threading/AsyncSleep.spec.ts | 54 ++++++++++--------- 35 files changed, 189 insertions(+), 187 deletions(-) diff --git a/src/application/ApplicationFactory.ts b/src/application/ApplicationFactory.ts index c737a780..99a06d45 100644 --- a/src/application/ApplicationFactory.ts +++ b/src/application/ApplicationFactory.ts @@ -15,7 +15,7 @@ export class ApplicationFactory implements IApplicationFactory { } this.getter = new AsyncLazy(() => Promise.resolve(costlyGetter())); } - public getAppAsync(): Promise { - return this.getter.getValueAsync(); + public getApp(): Promise { + return this.getter.getValue(); } } diff --git a/src/application/Context/ApplicationContextFactory.ts b/src/application/Context/ApplicationContextFactory.ts index e3000ae7..a120867f 100644 --- a/src/application/Context/ApplicationContextFactory.ts +++ b/src/application/Context/ApplicationContextFactory.ts @@ -7,12 +7,12 @@ import { IEnvironment } from '../Environment/IEnvironment'; import { IApplicationFactory } from '../IApplicationFactory'; import { ApplicationFactory } from '../ApplicationFactory'; -export async function buildContextAsync( +export async function buildContext( factory: IApplicationFactory = ApplicationFactory.Current, environment = Environment.CurrentEnvironment): Promise { if (!factory) { throw new Error('undefined factory'); } if (!environment) { throw new Error('undefined environment'); } - const app = await factory.getAppAsync(); + const app = await factory.getApp(); const os = getInitialOs(app, environment); return new ApplicationContext(app, os); } diff --git a/src/application/IApplicationFactory.ts b/src/application/IApplicationFactory.ts index a0cca695..85c3d69d 100644 --- a/src/application/IApplicationFactory.ts +++ b/src/application/IApplicationFactory.ts @@ -1,5 +1,5 @@ import { IApplication } from '@/domain/IApplication'; export interface IApplicationFactory { - getAppAsync(): Promise; + getApp(): Promise; } diff --git a/src/infrastructure/CodeRunner.ts b/src/infrastructure/CodeRunner.ts index f687783b..96e17dcb 100644 --- a/src/infrastructure/CodeRunner.ts +++ b/src/infrastructure/CodeRunner.ts @@ -10,7 +10,7 @@ export class CodeRunner { private readonly node = getNodeJs(), private readonly environment = Environment.CurrentEnvironment) { } - public async runCodeAsync(code: string, folderName: string, fileExtension: string): Promise { + public async runCode(code: string, folderName: string, fileExtension: string): Promise { const dir = this.node.path.join(this.node.os.tmpdir(), folderName); await this.node.fs.promises.mkdir(dir, {recursive: true}); const filePath = this.node.path.join(dir, `run.${fileExtension}`); diff --git a/src/infrastructure/Threading/AsyncLazy.ts b/src/infrastructure/Threading/AsyncLazy.ts index 7a3291a1..2332d45c 100644 --- a/src/infrastructure/Threading/AsyncLazy.ts +++ b/src/infrastructure/Threading/AsyncLazy.ts @@ -12,7 +12,7 @@ export class AsyncLazy { this.valueFactory = valueFactory; } - public async getValueAsync(): Promise { + public async getValue(): Promise { // If value is already created, return the value directly if (this.isValueCreated) { return Promise.resolve(this.value); diff --git a/src/infrastructure/Threading/AsyncSleep.ts b/src/infrastructure/Threading/AsyncSleep.ts index ff0388af..869cf5c0 100644 --- a/src/infrastructure/Threading/AsyncSleep.ts +++ b/src/infrastructure/Threading/AsyncSleep.ts @@ -1,5 +1,5 @@ export type SchedulerType = (callback: (...args: any[]) => void, ms: number) => void; -export function sleepAsync(time: number, scheduler: SchedulerType = setTimeout) { +export function sleep(time: number, scheduler: SchedulerType = setTimeout) { return new Promise((resolve) => scheduler(() => resolve(undefined), time)); } diff --git a/src/presentation/components/Code/CodeButtons/MacOsInstructions.vue b/src/presentation/components/Code/CodeButtons/MacOsInstructions.vue index 19ddb638..3dd54b12 100644 --- a/src/presentation/components/Code/CodeButtons/MacOsInstructions.vue +++ b/src/presentation/components/Code/CodeButtons/MacOsInstructions.vue @@ -96,7 +96,7 @@ export default class MacOsInstructions extends Vue { public macOsDownloadUrl = ''; public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.appName = app.info.name; this.macOsDownloadUrl = app.info.getDownloadUrl(OperatingSystem.macOS); } diff --git a/src/presentation/components/Code/CodeButtons/TheCodeButtons.vue b/src/presentation/components/Code/CodeButtons/TheCodeButtons.vue index dd7b8716..e0c5d5ff 100644 --- a/src/presentation/components/Code/CodeButtons/TheCodeButtons.vue +++ b/src/presentation/components/Code/CodeButtons/TheCodeButtons.vue @@ -3,18 +3,18 @@ @@ -54,20 +54,20 @@ export default class TheCodeButtons extends StatefulVue { public isMacOsCollection = false; public fileName = ''; - public async copyCodeAsync() { - const code = await this.getCurrentCodeAsync(); + public async copyCode() { + const code = await this.getCurrentCode(); Clipboard.copyText(code.current); } - public async saveCodeAsync() { - const context = await this.getCurrentContextAsync(); + public async saveCode() { + const context = await this.getCurrentContext(); saveCode(this.fileName, context.state); if (this.isMacOsCollection) { (this.$refs.instructionsDialog as any).show(); } } - public async executeCodeAsync() { - const context = await this.getCurrentContextAsync(); - await executeCodeAsync(context); + public async executeCode() { + const context = await this.getCurrentContext(); + await executeCode(context); } protected handleCollectionState(newState: ICategoryCollectionState): void { @@ -77,8 +77,8 @@ export default class TheCodeButtons extends StatefulVue { this.react(newState.code); } - private async getCurrentCodeAsync(): Promise { - const context = await this.getCurrentContextAsync(); + private async getCurrentCode(): Promise { + const context = await this.getCurrentContext(); const code = context.state.code; return code; } @@ -115,9 +115,9 @@ function buildFileName(scripting: IScriptingDefinition) { return fileName; } -async function executeCodeAsync(context: IApplicationContext) { +async function executeCode(context: IApplicationContext) { const runner = new CodeRunner(); - await runner.runCodeAsync( + await runner.runCode( /*code*/ context.state.code.current, /*appName*/ context.app.info.name, /*fileExtension*/ context.state.collection.scripting.fileExtension, diff --git a/src/presentation/components/Code/TheCodeArea.vue b/src/presentation/components/Code/TheCodeArea.vue index 60094da4..3507923a 100644 --- a/src/presentation/components/Code/TheCodeArea.vue +++ b/src/presentation/components/Code/TheCodeArea.vue @@ -51,13 +51,13 @@ export default class TheCodeArea extends StatefulVue { const appCode = newState.code; this.editor.setValue(appCode.current || getDefaultCode(newState.collection.scripting.language), 1); this.events.unsubscribeAll(); - this.events.register(appCode.changed.on((code) => this.updateCodeAsync(code))); + this.events.register(appCode.changed.on((code) => this.updateCode(code))); } - private async updateCodeAsync(event: ICodeChangedEvent) { + private async updateCode(event: ICodeChangedEvent) { this.removeCurrentHighlighting(); if (event.isEmpty()) { - const context = await this.getCurrentContextAsync(); + const context = await this.getCurrentContext(); const defaultCode = getDefaultCode(context.state.collection.scripting.language); this.editor.setValue(defaultCode, 1); return; diff --git a/src/presentation/components/Scripts/Menu/TheOsChanger.vue b/src/presentation/components/Scripts/Menu/TheOsChanger.vue index 3150b481..53251193 100644 --- a/src/presentation/components/Scripts/Menu/TheOsChanger.vue +++ b/src/presentation/components/Scripts/Menu/TheOsChanger.vue @@ -3,7 +3,7 @@ @@ -29,12 +29,12 @@ export default class TheOsChanger extends StatefulVue { public currentOs?: OperatingSystem = null; public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.allOses = app.getSupportedOsList() .map((os) => ({ os, name: renderOsName(os) })); } - public async changeOsAsync(newOs: OperatingSystem) { - const context = await this.getCurrentContextAsync(); + public async changeOs(newOs: OperatingSystem) { + const context = await this.getCurrentContext(); context.changeContext(newOs); } diff --git a/src/presentation/components/Scripts/View/Cards/CardListItem.vue b/src/presentation/components/Scripts/View/Cards/CardListItem.vue index 4ef49841..b9a60dda 100644 --- a/src/presentation/components/Scripts/View/Cards/CardListItem.vue +++ b/src/presentation/components/Scripts/View/Cards/CardListItem.vue @@ -50,10 +50,10 @@ export default class CardListItem extends StatefulVue { public areAllChildrenSelected = false; public async mounted() { - const context = await this.getCurrentContextAsync(); + const context = await this.getCurrentContext(); this.events.register(context.state.selection.changed.on( - () => this.updateSelectionIndicatorsAsync(this.categoryId))); - await this.updateStateAsync(this.categoryId); + () => this.updateSelectionIndicators(this.categoryId))); + await this.updateState(this.categoryId); } @Emit('selected') public onSelected(isExpanded: boolean) { @@ -64,7 +64,7 @@ export default class CardListItem extends StatefulVue { this.isExpanded = value === this.categoryId; } @Watch('isExpanded') - public async onExpansionChangedAsync(newValue: number, oldValue: number) { + public async onExpansionChanged(newValue: number, oldValue: number) { if (!oldValue && newValue) { await new Promise((r) => setTimeout(r, 400)); const focusElement = this.$refs.cardElement as HTMLElement; @@ -72,19 +72,19 @@ export default class CardListItem extends StatefulVue { } } @Watch('categoryId') - public async updateStateAsync(value: |number) { - const context = await this.getCurrentContextAsync(); + public async updateState(value: |number) { + const context = await this.getCurrentContext(); const category = !value ? undefined : context.state.collection.findCategory(value); this.cardTitle = category ? category.name : undefined; - await this.updateSelectionIndicatorsAsync(value); + await this.updateSelectionIndicators(value); } protected handleCollectionState(): void { return; } - private async updateSelectionIndicatorsAsync(categoryId: number) { - const context = await this.getCurrentContextAsync(); + private async updateSelectionIndicators(categoryId: number) { + const context = await this.getCurrentContext(); const selection = context.state.selection; const category = context.state.collection.findCategory(categoryId); this.isAnyChildSelected = category ? selection.isAnySelected(category) : false; diff --git a/src/presentation/components/Scripts/View/ScriptsTree/ScriptsTree.vue b/src/presentation/components/Scripts/View/ScriptsTree/ScriptsTree.vue index 7180c7b8..abea72aa 100644 --- a/src/presentation/components/Scripts/View/ScriptsTree/ScriptsTree.vue +++ b/src/presentation/components/Scripts/View/ScriptsTree/ScriptsTree.vue @@ -6,7 +6,7 @@ :selectedNodeIds="selectedNodeIds" :filterPredicate="filterPredicate" :filterText="filterText" - v-on:nodeSelected="toggleNodeSelectionAsync($event)" + v-on:nodeSelected="toggleNodeSelection($event)" > @@ -42,8 +42,8 @@ export default class ScriptsTree extends StatefulVue { private filtered?: IFilterResult; - public async toggleNodeSelectionAsync(event: INodeSelectedEvent) { - const context = await this.getCurrentContextAsync(); + public async toggleNodeSelection(event: INodeSelectedEvent) { + const context = await this.getCurrentContext(); switch (event.node.type) { case NodeType.Category: toggleCategoryNodeSelection(event, context.state); @@ -56,8 +56,8 @@ export default class ScriptsTree extends StatefulVue { } } @Watch('categoryId', { immediate: true }) - public async setNodesAsync(categoryId?: number) { - const context = await this.getCurrentContextAsync(); + public async setNodes(categoryId?: number) { + const context = await this.getCurrentContext(); if (categoryId) { this.nodes = parseSingleCategory(categoryId, context.state.collection); } else { diff --git a/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/Node/RevertToggle.vue b/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/Node/RevertToggle.vue index a2b9c896..0e0aa77c 100644 --- a/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/Node/RevertToggle.vue +++ b/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/Node/RevertToggle.vue @@ -2,7 +2,7 @@
revert @@ -28,12 +28,12 @@ export default class RevertToggle extends StatefulVue { private handler: IReverter; - @Watch('node', {immediate: true}) public async onNodeChangedAsync(node: INode) { - const context = await this.getCurrentContextAsync(); + @Watch('node', {immediate: true}) public async onNodeChanged(node: INode) { + const context = await this.getCurrentContext(); this.handler = getReverter(node, context.state.collection); } - public async onRevertToggledAsync() { - const context = await this.getCurrentContextAsync(); + public async onRevertToggled() { + const context = await this.getCurrentContext(); this.handler.selectWithRevertState(this.isReverted, context.state.selection); } diff --git a/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/SelectableTree.vue b/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/SelectableTree.vue index 8746c433..c376b5f0 100644 --- a/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/SelectableTree.vue +++ b/src/presentation/components/Scripts/View/ScriptsTree/SelectableTree/SelectableTree.vue @@ -23,7 +23,7 @@ import Node from './Node/Node.vue'; import { INode } from './Node/INode'; import { convertExistingToNode, toNewLiquorTreeNode } from './LiquorTree/NodeWrapper/NodeTranslator'; import { INodeSelectedEvent } from './INodeSelectedEvent'; -import { sleepAsync } from '@/infrastructure/Threading/AsyncSleep'; +import { sleep } from '@/infrastructure/Threading/AsyncSleep'; import { getNewState } from './LiquorTree/NodeWrapper/NodeStateUpdater'; import { LiquorTreeOptions } from './LiquorTree/LiquorTreeOptions'; import { FilterPredicate, NodePredicateFilter } from './LiquorTree/NodeWrapper/NodePredicateFilter'; @@ -56,7 +56,7 @@ export default class SelectableTree extends Vue { // Keep it stateless to make i } @Watch('initialNodes', { immediate: true }) - public async updateNodesAsync(nodes: readonly INode[]) { + public async updateNodes(nodes: readonly INode[]) { if (!nodes) { throw new Error('undefined initial nodes'); } @@ -66,12 +66,12 @@ export default class SelectableTree extends Vue { // Keep it stateless to make i (node) => node.state = updateState(node.state, node, this.selectedNodeIds)); } this.initialLiquourTreeNodes = initialNodes; - const api = await this.getLiquorTreeApiAsync(); + const api = await this.getLiquorTreeApi(); api.setModel(this.initialLiquourTreeNodes); // as liquor tree is not reactive to data after initialization } @Watch('filterText', { immediate: true }) - public async updateFilterTextAsync(filterText: |string) { - const api = await this.getLiquorTreeApiAsync(); + public async updateFilterText(filterText: |string) { + const api = await this.getLiquorTreeApi(); if (!filterText) { api.clearFilter(); } else { @@ -80,22 +80,22 @@ export default class SelectableTree extends Vue { // Keep it stateless to make i } @Watch('selectedNodeIds') - public async setSelectedStatusAsync(selectedNodeIds: ReadonlyArray) { + public async setSelectedStatus(selectedNodeIds: ReadonlyArray) { if (!selectedNodeIds) { throw new Error('SelectedrecurseDown nodes are undefined'); } - const tree = await this.getLiquorTreeApiAsync(); + const tree = await this.getLiquorTreeApi(); tree.recurseDown( (node) => node.states = updateState(node.states, node, selectedNodeIds), ); } - private async getLiquorTreeApiAsync(): Promise { + private async getLiquorTreeApi(): Promise { const accessor = (): ILiquorTree => { const uiElement = this.$refs.treeElement; return uiElement ? (uiElement as any).tree : undefined; }; - const treeElement = await tryUntilDefinedAsync(accessor, 5, 20); // Wait for it to render + const treeElement = await tryUntilDefined(accessor, 5, 20); // Wait for it to render if (!treeElement) { throw Error('Referenced tree element cannot be found. Perhaps it\'s not yet rendered?'); } @@ -119,7 +119,7 @@ function recurseDown( } } } -async function tryUntilDefinedAsync( +async function tryUntilDefined( accessor: () => T | undefined, delayInMs: number, maxTries: number): Promise { let triesLeft = maxTries; @@ -130,7 +130,7 @@ async function tryUntilDefinedAsync( return value; } triesLeft--; - await sleepAsync(delayInMs); + await sleep(delayInMs); } return value; } diff --git a/src/presentation/components/Scripts/View/TheScriptsView.vue b/src/presentation/components/Scripts/View/TheScriptsView.vue index 406a820b..8579e013 100644 --- a/src/presentation/components/Scripts/View/TheScriptsView.vue +++ b/src/presentation/components/Scripts/View/TheScriptsView.vue @@ -13,7 +13,7 @@
+ v-on:click="clearSearchQuery()"/>
@@ -65,11 +65,11 @@ export default class TheScriptsView extends StatefulVue { public ViewType = ViewType; // Make it accessible from the view public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.repositoryUrl = app.info.repositoryWebUrl; } - public async clearSearchQueryAsync() { - const context = await this.getCurrentContextAsync(); + public async clearSearchQuery() { + const context = await this.getCurrentContext(); const filter = context.state.filter; filter.removeFilter(); } diff --git a/src/presentation/components/Shared/StatefulVue.ts b/src/presentation/components/Shared/StatefulVue.ts index bb334009..2f761d99 100644 --- a/src/presentation/components/Shared/StatefulVue.ts +++ b/src/presentation/components/Shared/StatefulVue.ts @@ -1,7 +1,7 @@ import { Component, Vue } from 'vue-property-decorator'; import { AsyncLazy } from '@/infrastructure/Threading/AsyncLazy'; import { IApplicationContext } from '@/application/Context/IApplicationContext'; -import { buildContextAsync } from '@/application/Context/ApplicationContextFactory'; +import { buildContext } from '@/application/Context/ApplicationContextFactory'; import { IApplicationContextChangedEvent } from '@/application/Context/IApplicationContext'; import { ICategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState'; import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection'; @@ -9,14 +9,14 @@ import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscr // @ts-ignore because https://github.com/vuejs/vue-class-component/issues/91 @Component export abstract class StatefulVue extends Vue { - private static readonly instance = new AsyncLazy(() => buildContextAsync()); + private static readonly instance = new AsyncLazy(() => buildContext()); protected readonly events = new EventSubscriptionCollection(); private readonly ownEvents = new EventSubscriptionCollection(); public async mounted() { - const context = await this.getCurrentContextAsync(); + const context = await this.getCurrentContext(); this.ownEvents.register(context.contextChanged.on((event) => this.handleStateChangedEvent(event))); this.handleCollectionState(context.state, undefined); } @@ -27,8 +27,8 @@ export abstract class StatefulVue extends Vue { protected abstract handleCollectionState( newState: ICategoryCollectionState, oldState: ICategoryCollectionState | undefined): void; - protected getCurrentContextAsync(): Promise { - return StatefulVue.instance.getValueAsync(); + protected getCurrentContext(): Promise { + return StatefulVue.instance.getValue(); } private handleStateChangedEvent(event: IApplicationContextChangedEvent) { diff --git a/src/presentation/components/TheFooter/DownloadUrlListItem.vue b/src/presentation/components/TheFooter/DownloadUrlListItem.vue index 8ff68bc9..65413de2 100644 --- a/src/presentation/components/TheFooter/DownloadUrlListItem.vue +++ b/src/presentation/components/TheFooter/DownloadUrlListItem.vue @@ -24,20 +24,20 @@ export default class DownloadUrlListItem extends Vue { public hasCurrentOsDesktopVersion: boolean = false; public async mounted() { - await this.onOperatingSystemChangedAsync(this.operatingSystem); + await this.onOperatingSystemChanged(this.operatingSystem); } @Watch('operatingSystem') - public async onOperatingSystemChangedAsync(os: OperatingSystem) { + public async onOperatingSystemChanged(os: OperatingSystem) { const currentOs = Environment.CurrentEnvironment.os; this.isCurrentOs = os === currentOs; - this.downloadUrl = await this.getDownloadUrlAsync(os); + this.downloadUrl = await this.getDownloadUrl(os); this.operatingSystemName = getOperatingSystemName(os); this.hasCurrentOsDesktopVersion = hasDesktopVersion(currentOs); } - private async getDownloadUrlAsync(os: OperatingSystem): Promise { - const context = await ApplicationFactory.Current.getAppAsync(); + private async getDownloadUrl(os: OperatingSystem): Promise { + const context = await ApplicationFactory.Current.getApp(); return context.info.getDownloadUrl(os); } } diff --git a/src/presentation/components/TheFooter/PrivacyPolicy.vue b/src/presentation/components/TheFooter/PrivacyPolicy.vue index 47511863..2032dcf0 100644 --- a/src/presentation/components/TheFooter/PrivacyPolicy.vue +++ b/src/presentation/components/TheFooter/PrivacyPolicy.vue @@ -43,7 +43,7 @@ export default class PrivacyPolicy extends Vue { public isDesktop = Environment.CurrentEnvironment.isDesktop; public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.initialize(app); } diff --git a/src/presentation/components/TheFooter/TheFooter.vue b/src/presentation/components/TheFooter/TheFooter.vue index cdfa6799..4ace01d0 100644 --- a/src/presentation/components/TheFooter/TheFooter.vue +++ b/src/presentation/components/TheFooter/TheFooter.vue @@ -65,7 +65,7 @@ export default class TheFooter extends Vue { public homepageUrl: string = ''; public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.initialize(app); } diff --git a/src/presentation/components/TheHeader.vue b/src/presentation/components/TheHeader.vue index 0e8a3888..25b902ee 100644 --- a/src/presentation/components/TheHeader.vue +++ b/src/presentation/components/TheHeader.vue @@ -15,7 +15,7 @@ export default class TheHeader extends Vue { public subtitle = ''; public async created() { - const app = await ApplicationFactory.Current.getAppAsync(); + const app = await ApplicationFactory.Current.getApp(); this.title = app.info.name; } } diff --git a/src/presentation/components/TheSearchBar.vue b/src/presentation/components/TheSearchBar.vue index 56300660..39573fe3 100644 --- a/src/presentation/components/TheSearchBar.vue +++ b/src/presentation/components/TheSearchBar.vue @@ -26,8 +26,8 @@ export default class TheSearchBar extends StatefulVue { public searchQuery = ''; @Watch('searchQuery') - public async updateFilterAsync(newFilter: |string) { - const context = await this.getCurrentContextAsync(); + public async updateFilter(newFilter: |string) { + const context = await this.getCurrentContext(); const filter = context.state.filter; if (!newFilter) { filter.removeFilter(); diff --git a/src/presentation/electron/Update/AutoUpdater.ts b/src/presentation/electron/Update/AutoUpdater.ts index 7682e891..c2c9d80a 100644 --- a/src/presentation/electron/Update/AutoUpdater.ts +++ b/src/presentation/electron/Update/AutoUpdater.ts @@ -4,8 +4,8 @@ import { ProgressInfo } from 'electron-builder'; import { UpdateProgressBar } from './UpdateProgressBar'; import log from 'electron-log'; -export async function handleAutoUpdateAsync() { - if (await askDownloadAndInstallAsync() === DownloadDialogResult.NotNow) { +export async function handleAutoUpdate() { + if (await askDownloadAndInstall() === DownloadDialogResult.NotNow) { return; } startHandlingUpdateProgress(); @@ -29,12 +29,12 @@ function startHandlingUpdateProgress() { autoUpdater.on('update-downloaded', async (info: UpdateInfo) => { log.info('@update-downloaded@\n', info); progressBar.close(); - await handleUpdateDownloadedAsync(); + await handleUpdateDownloaded(); }); } -async function handleUpdateDownloadedAsync() { - if (await askRestartAndInstallAsync() === InstallDialogResult.NotNow) { +async function handleUpdateDownloaded() { + if (await askRestartAndInstall() === InstallDialogResult.NotNow) { return; } setTimeout(() => autoUpdater.quitAndInstall(), 1); @@ -44,7 +44,7 @@ enum DownloadDialogResult { Install = 0, NotNow = 1, } -async function askDownloadAndInstallAsync(): Promise { +async function askDownloadAndInstall(): Promise { const updateDialogResult = await dialog.showMessageBox({ type: 'question', buttons: ['Install', 'Not now' ], @@ -61,7 +61,7 @@ enum InstallDialogResult { InstallAndRestart = 0, NotNow = 1, } -async function askRestartAndInstallAsync(): Promise { +async function askRestartAndInstall(): Promise { const installDialogResult = await dialog.showMessageBox({ type: 'question', buttons: ['Install and restart', 'Later'], diff --git a/src/presentation/electron/Update/ManualUpdater.ts b/src/presentation/electron/Update/ManualUpdater.ts index d476e5e1..a4907c9c 100644 --- a/src/presentation/electron/Update/ManualUpdater.ts +++ b/src/presentation/electron/Update/ManualUpdater.ts @@ -12,8 +12,8 @@ export function requiresManualUpdate(): boolean { return process.platform === 'darwin'; } -export async function handleManualUpdateAsync(info: UpdateInfo) { - const result = await askForVisitingWebsiteForManualUpdateAsync(); +export async function handleManualUpdate(info: UpdateInfo) { + const result = await askForVisitingWebsiteForManualUpdate(); if (result === ManualDownloadDialogResult.NoAction) { return; } @@ -26,7 +26,7 @@ export async function handleManualUpdateAsync(info: UpdateInfo) { if (result === ManualDownloadDialogResult.VisitReleasesPage) { await shell.openExternal(project.releaseUrl); } else if (result === ManualDownloadDialogResult.UpdateNow) { - await downloadAsync(info, project); + await download(info, project); } } @@ -35,7 +35,7 @@ enum ManualDownloadDialogResult { UpdateNow = 1, VisitReleasesPage = 2, } -async function askForVisitingWebsiteForManualUpdateAsync(): Promise { +async function askForVisitingWebsiteForManualUpdate(): Promise { const visitPageResult = await dialog.showMessageBox({ type: 'info', buttons: [ @@ -54,7 +54,7 @@ async function askForVisitingWebsiteForManualUpdateAsync(): Promise { progressBar.showPercentage(percentage); }); await shell.openPath(filePath); progressBar.close(); @@ -81,7 +81,7 @@ async function downloadAsync(info: UpdateInfo, project: ProjectInformation) { type ProgressCallback = (progress: number) => void; -async function downloadFileWithProgressAsync( +async function downloadFileWithProgress( url: string, filePath: string, progressHandler: ProgressCallback) { // We don't download through autoUpdater as it cannot download DMG but requires distributing ZIP log.info(`Fetching ${url}`); @@ -100,10 +100,10 @@ async function downloadFileWithProgressAsync( if (!reader) { throw new Error('No response body'); } - await streamWithProgressAsync(contentLength, reader, writer, progressHandler); + await streamWithProgress(contentLength, reader, writer, progressHandler); } -async function streamWithProgressAsync( +async function streamWithProgress( totalLength: number, readStream: NodeJS.ReadableStream, writeStream: fs.WriteStream, diff --git a/src/presentation/electron/Update/Updater.ts b/src/presentation/electron/Update/Updater.ts index f87644cd..52ad0101 100644 --- a/src/presentation/electron/Update/Updater.ts +++ b/src/presentation/electron/Update/Updater.ts @@ -1,10 +1,10 @@ import { autoUpdater, UpdateInfo } from 'electron-updater'; import log from 'electron-log'; -import { handleManualUpdateAsync, requiresManualUpdate } from './ManualUpdater'; -import { handleAutoUpdateAsync } from './AutoUpdater'; +import { handleManualUpdate, requiresManualUpdate } from './ManualUpdater'; +import { handleAutoUpdate } from './AutoUpdater'; interface IUpdater { - checkForUpdatesAsync(): Promise; + checkForUpdates(): Promise; } export function setupAutoUpdater(): IUpdater { @@ -21,20 +21,20 @@ export function setupAutoUpdater(): IUpdater { return; } isAlreadyHandled = true; - await handleAvailableUpdateAsync(info); + await handleAvailableUpdate(info); }); return { - checkForUpdatesAsync: async () => { + checkForUpdates: async () => { // autoUpdater.emit('update-available'); // For testing await autoUpdater.checkForUpdates(); }, }; } -async function handleAvailableUpdateAsync(info: UpdateInfo) { +async function handleAvailableUpdate(info: UpdateInfo) { if (requiresManualUpdate()) { - await handleManualUpdateAsync(info); + await handleManualUpdate(info); return; } - await handleAutoUpdateAsync(); + await handleAutoUpdate(); } diff --git a/src/presentation/electron/main.ts b/src/presentation/electron/main.ts index 196406a1..6b84dd26 100644 --- a/src/presentation/electron/main.ts +++ b/src/presentation/electron/main.ts @@ -124,7 +124,7 @@ function loadApplication(window: BrowserWindow) { // Load the index.html when not in development loadUrlWithNodeWorkaround(win, 'app://./index.html'); const updater = setupAutoUpdater(); - updater.checkForUpdatesAsync(); + updater.checkForUpdates(); } } diff --git a/tests/integration/application/collections/NoDeadDocumentationUrls.spec.ts b/tests/integration/application/collections/NoDeadDocumentationUrls.spec.ts index f42a4b89..323e1fd0 100644 --- a/tests/integration/application/collections/NoDeadDocumentationUrls.spec.ts +++ b/tests/integration/application/collections/NoDeadDocumentationUrls.spec.ts @@ -3,7 +3,7 @@ import { expect } from 'chai'; import { parseApplication } from '@/application/Parser/ApplicationParser'; import { IApplication } from '@/domain/IApplication'; import { IUrlStatus } from './StatusChecker/IUrlStatus'; -import { getUrlStatusesInParallelAsync, IBatchRequestOptions } from './StatusChecker/BatchStatusChecker'; +import { getUrlStatusesInParallel, IBatchRequestOptions } from './StatusChecker/BatchStatusChecker'; describe('collections', () => { // arrange @@ -25,7 +25,7 @@ describe('collections', () => { const testTimeoutInMs = urls.length * 60000 /* 1 minute */; it('have no dead urls', async () => { // act - const results = await getUrlStatusesInParallelAsync(urls, options); + const results = await getUrlStatusesInParallel(urls, options); // assert const deadUrls = results.filter((r) => r.code !== 200); expect(deadUrls).to.have.lengthOf(0, printUrls(deadUrls)); diff --git a/tests/integration/application/collections/StatusChecker/BatchStatusChecker.ts b/tests/integration/application/collections/StatusChecker/BatchStatusChecker.ts index 81a3735c..62d50d91 100644 --- a/tests/integration/application/collections/StatusChecker/BatchStatusChecker.ts +++ b/tests/integration/application/collections/StatusChecker/BatchStatusChecker.ts @@ -1,16 +1,16 @@ -import { sleepAsync } from '@/infrastructure/Threading/AsyncSleep'; +import { sleep } from '@/infrastructure/Threading/AsyncSleep'; import { IUrlStatus } from './IUrlStatus'; -import { getUrlStatusAsync, IRequestOptions } from './Requestor'; +import { getUrlStatus, IRequestOptions } from './Requestor'; import { groupUrlsByDomain } from './UrlPerDomainGrouper'; -export async function getUrlStatusesInParallelAsync( +export async function getUrlStatusesInParallel( urls: string[], options?: IBatchRequestOptions): Promise { // urls = [ 'https://privacy.sexy' ]; // Here to comment out when testing const uniqueUrls = Array.from(new Set(urls)); options = { ...DefaultOptions, ...options }; console.log('Options: ', options); // tslint:disable-line: no-console - const results = await requestAsync(uniqueUrls, options); + const results = await request(uniqueUrls, options); return results; } @@ -35,19 +35,19 @@ const DefaultOptions: IBatchRequestOptions = { }, }; -function requestAsync(urls: string[], options: IBatchRequestOptions): Promise { +function request(urls: string[], options: IBatchRequestOptions): Promise { if (!options.domainOptions.sameDomainParallelize) { - return runOnEachDomainWithDelayAsync( + return runOnEachDomainWithDelay( urls, - (url) => getUrlStatusAsync(url, options.requestOptions), + (url) => getUrlStatus(url, options.requestOptions), options.domainOptions.sameDomainDelayInMs); } else { return Promise.all( - urls.map((url) => getUrlStatusAsync(url, options.requestOptions))); + urls.map((url) => getUrlStatus(url, options.requestOptions))); } } -async function runOnEachDomainWithDelayAsync( +async function runOnEachDomainWithDelay( urls: string[], action: (url: string) => Promise, delayInMs: number): Promise { @@ -58,7 +58,7 @@ async function runOnEachDomainWithDelayAsync( const status = await action(url); results.push(status); if (results.length !== group.length) { - await sleepAsync(delayInMs); + await sleep(delayInMs); } } return results; diff --git a/tests/integration/application/collections/StatusChecker/ExponentialBackOffRetryHandler.ts b/tests/integration/application/collections/StatusChecker/ExponentialBackOffRetryHandler.ts index ea1fcfaf..fdfcf19c 100644 --- a/tests/integration/application/collections/StatusChecker/ExponentialBackOffRetryHandler.ts +++ b/tests/integration/application/collections/StatusChecker/ExponentialBackOffRetryHandler.ts @@ -1,9 +1,9 @@ -import { sleepAsync } from '@/infrastructure/Threading/AsyncSleep'; +import { sleep } from '@/infrastructure/Threading/AsyncSleep'; import { IUrlStatus } from './IUrlStatus'; const DefaultBaseRetryIntervalInMs = 5 /* sec */ * 1000; -export async function retryWithExponentialBackOffAsync( +export async function retryWithExponentialBackOff( action: () => Promise, baseRetryIntervalInMs: number = DefaultBaseRetryIntervalInMs, currentRetry = 1): Promise { @@ -14,8 +14,8 @@ export async function retryWithExponentialBackOffAsync( const exponentialBackOffInMs = getRetryTimeoutInMs(currentRetry, baseRetryIntervalInMs); // tslint:disable-next-line: no-console console.log(`Retrying (${currentRetry}) in ${exponentialBackOffInMs / 1000} seconds`, status); - await sleepAsync(exponentialBackOffInMs); - return retryWithExponentialBackOffAsync(action, baseRetryIntervalInMs, currentRetry + 1); + await sleep(exponentialBackOffInMs); + return retryWithExponentialBackOff(action, baseRetryIntervalInMs, currentRetry + 1); } } return status; diff --git a/tests/integration/application/collections/StatusChecker/README.md b/tests/integration/application/collections/StatusChecker/README.md index ad5b0770..4cb9bafe 100644 --- a/tests/integration/application/collections/StatusChecker/README.md +++ b/tests/integration/application/collections/StatusChecker/README.md @@ -21,11 +21,11 @@ Coming soon 🚧 Programmatic usage is supported both on Node.js and browser. -### `getUrlStatusesInParallelAsync` +### `getUrlStatusesInParallel` ```js // Simple example -const statuses = await getUrlStatusesInParallelAsync([ 'https://privacy.sexy', /* ... */ ]); +const statuses = await getUrlStatusesInParallel([ 'https://privacy.sexy', /* ... */ ]); if(statuses.all((r) => r.code === 200)) { console.log('All URLs are alive!'); } else { @@ -33,7 +33,7 @@ if(statuses.all((r) => r.code === 200)) { } // Fastest configuration -const statuses = await getUrlStatusesInParallelAsync([ 'https://privacy.sexy', /* ... */ ], { +const statuses = await getUrlStatusesInParallel([ 'https://privacy.sexy', /* ... */ ], { domainOptions: { sameDomainParallelize: false, } @@ -53,13 +53,13 @@ const statuses = await getUrlStatusesInParallelAsync([ 'https://privacy.sexy', / - Sets delay between requests to same host (domain) if same domain parallelization is disabled. - `requestOptions` (*object*): See [request options](#request-options). -### `getUrlStatusAsync` +### `getUrlStatus` Checks whether single URL is dead or alive. ```js // Simple example -const status = await getUrlStatusAsync('https://privacy.sexy'); +const status = await getUrlStatus('https://privacy.sexy'); console.log(`Status code: ${status.code}`); ``` diff --git a/tests/integration/application/collections/StatusChecker/Requestor.ts b/tests/integration/application/collections/StatusChecker/Requestor.ts index 106e1163..305d45bf 100644 --- a/tests/integration/application/collections/StatusChecker/Requestor.ts +++ b/tests/integration/application/collections/StatusChecker/Requestor.ts @@ -1,13 +1,13 @@ -import { retryWithExponentialBackOffAsync } from './ExponentialBackOffRetryHandler'; +import { retryWithExponentialBackOff } from './ExponentialBackOffRetryHandler'; import { IUrlStatus } from './IUrlStatus'; import { fetchFollow, IFollowOptions } from './FetchFollow'; -export async function getUrlStatusAsync( +export async function getUrlStatus( url: string, options: IRequestOptions = DefaultOptions): Promise { options = { ...DefaultOptions, ...options }; const fetchOptions = getFetchOptions(url, options); - return retryWithExponentialBackOffAsync(async () => { + return retryWithExponentialBackOff(async () => { console.log('Requesting', url); // tslint:disable-line: no-console let result: IUrlStatus; try { diff --git a/tests/unit/application/ApplicationFactory.spec.ts b/tests/unit/application/ApplicationFactory.spec.ts index a991ebb2..61eb5ee8 100644 --- a/tests/unit/application/ApplicationFactory.spec.ts +++ b/tests/unit/application/ApplicationFactory.spec.ts @@ -15,7 +15,7 @@ describe('ApplicationFactory', () => { expect(act).to.throw(expectedError); }); }); - describe('getAppAsync', () => { + describe('getApp', () => { it('returns result from the getter', async () => { // arrange const expected = new ApplicationStub(); @@ -23,10 +23,10 @@ describe('ApplicationFactory', () => { const sut = new SystemUnderTest(getter); // act const actual = await Promise.all( [ - sut.getAppAsync(), - sut.getAppAsync(), - sut.getAppAsync(), - sut.getAppAsync(), + sut.getApp(), + sut.getApp(), + sut.getApp(), + sut.getApp(), ]); // assert expect(actual.every((value) => value === expected)); @@ -42,10 +42,10 @@ describe('ApplicationFactory', () => { const sut = new SystemUnderTest(getter); // act await Promise.all( [ - sut.getAppAsync(), - sut.getAppAsync(), - sut.getAppAsync(), - sut.getAppAsync(), + sut.getApp(), + sut.getApp(), + sut.getApp(), + sut.getApp(), ]); // assert expect(totalExecution).to.equal(1); diff --git a/tests/unit/application/Context/ApplicationContextFactory.spec.ts b/tests/unit/application/Context/ApplicationContextFactory.spec.ts index 61ff8784..8cdbfded 100644 --- a/tests/unit/application/Context/ApplicationContextFactory.spec.ts +++ b/tests/unit/application/Context/ApplicationContextFactory.spec.ts @@ -2,7 +2,7 @@ import 'mocha'; import { expect } from 'chai'; import { OperatingSystem } from '@/domain/OperatingSystem'; import { ICategoryCollection } from '@/domain/ICategoryCollection'; -import { buildContextAsync } from '@/application/Context/ApplicationContextFactory'; +import { buildContext } from '@/application/Context/ApplicationContextFactory'; import { IApplicationFactory } from '@/application/IApplicationFactory'; import { IApplication } from '@/domain/IApplication'; import { EnvironmentStub } from '@tests/unit/stubs/EnvironmentStub'; @@ -10,7 +10,7 @@ import { ApplicationStub } from '@tests/unit/stubs/ApplicationStub'; import { CategoryCollectionStub } from '@tests/unit/stubs/CategoryCollectionStub'; describe('ApplicationContextFactory', () => { - describe('buildContextAsync', () => { + describe('buildContext', () => { describe('factory', () => { it('sets application from factory', async () => { // arrange @@ -18,7 +18,7 @@ describe('ApplicationContextFactory', () => { new CategoryCollectionStub().withOs(OperatingSystem.macOS)); const factoryMock = mockFactoryWithApp(expected); // act - const context = await buildContextAsync(factoryMock); + const context = await buildContext(factoryMock); // assert expect(expected).to.equal(context.app); }); @@ -32,7 +32,7 @@ describe('ApplicationContextFactory', () => { const collection = new CategoryCollectionStub().withOs(expected); const factoryMock = mockFactoryWithCollection(collection); // act - const context = await buildContextAsync(factoryMock, environment); + const context = await buildContext(factoryMock, environment); // assert const actual = context.state.os; expect(expected).to.equal(actual); @@ -45,7 +45,7 @@ describe('ApplicationContextFactory', () => { const collection = new CategoryCollectionStub().withOs(expected); const factoryMock = mockFactoryWithCollection(collection); // act - const context = await buildContextAsync(factoryMock, environment); + const context = await buildContext(factoryMock, environment); // assert const actual = context.state.os; expect(expected).to.equal(actual); @@ -62,7 +62,7 @@ describe('ApplicationContextFactory', () => { const app = new ApplicationStub().withCollections(...allCollections); const factoryMock = mockFactoryWithApp(app); // act - const context = await buildContextAsync(factoryMock, environment); + const context = await buildContext(factoryMock, environment); // assert const actual = context.state.os; expect(expectedOs).to.equal(actual, `Expected: ${OperatingSystem[expectedOs]}, actual: ${OperatingSystem[actual]}`); @@ -78,6 +78,6 @@ function mockFactoryWithCollection(result: ICategoryCollection): IApplicationFac function mockFactoryWithApp(app: IApplication): IApplicationFactory { return { - getAppAsync: () => Promise.resolve(app), + getApp: () => Promise.resolve(app), }; } diff --git a/tests/unit/infrastructure/CodeRunner.spec.ts b/tests/unit/infrastructure/CodeRunner.spec.ts index 46a7ac34..0ad878cf 100644 --- a/tests/unit/infrastructure/CodeRunner.spec.ts +++ b/tests/unit/infrastructure/CodeRunner.spec.ts @@ -5,7 +5,7 @@ import { OperatingSystem } from '@/domain/OperatingSystem'; import { CodeRunner } from '@/infrastructure/CodeRunner'; describe('CodeRunner', () => { - describe('runCodeAsync', () => { + describe('runCode', () => { it('creates temporary directory recursively', async () => { // arrange const expectedDir = 'expected-dir'; @@ -17,7 +17,7 @@ describe('CodeRunner', () => { // act await context .withFolderName(folderName) - .runCodeAsync(); + .runCode(); // assert expect(context.mocks.fs.mkdirHistory.length).to.equal(1); @@ -42,7 +42,7 @@ describe('CodeRunner', () => { .withCode(expectedCode) .withFolderName(folderName) .withExtension(extension) - .runCodeAsync(); + .runCode(); // assert expect(context.mocks.fs.writeFileHistory.length).to.equal(1); @@ -66,7 +66,7 @@ describe('CodeRunner', () => { await context .withFolderName(folderName) .withExtension(extension) - .runCodeAsync(); + .runCode(); // assert expect(context.mocks.fs.chmodCallHistory.length).to.equal(1); @@ -93,7 +93,7 @@ describe('CodeRunner', () => { // act await context .withOs(data.os) - .runCodeAsync(); + .runCode(); // assert expect(context.mocks.child_process.executionHistory.length).to.equal(1); @@ -109,7 +109,7 @@ describe('CodeRunner', () => { context.mocks.path.setupJoinSequence('non-important-folder-name1', 'non-important-folder-name2'); // act - await context.runCodeAsync(); + await context.runCode(); // assert const actualOrder = context.mocks.commandHistory.filter((command) => expectedOrder.includes(command)); @@ -126,9 +126,9 @@ class TestContext { private fileExtension: string = 'fileExtension'; private env = mockEnvironment(OperatingSystem.Windows); - public async runCodeAsync(): Promise { + public async runCode(): Promise { const runner = new CodeRunner(this.mocks, this.env); - await runner.runCodeAsync(this.code, this.folderName, this.fileExtension); + await runner.runCode(this.code, this.folderName, this.fileExtension); } public withOs(os: OperatingSystem) { this.env = mockEnvironment(os); diff --git a/tests/unit/infrastructure/Threading/AsyncLazy.spec.ts b/tests/unit/infrastructure/Threading/AsyncLazy.spec.ts index 45ca1d15..714695ca 100644 --- a/tests/unit/infrastructure/Threading/AsyncLazy.spec.ts +++ b/tests/unit/infrastructure/Threading/AsyncLazy.spec.ts @@ -1,7 +1,7 @@ import 'mocha'; import { expect } from 'chai'; import { AsyncLazy } from '@/infrastructure/Threading/AsyncLazy'; -import { sleepAsync } from '@/infrastructure/Threading/AsyncSleep'; +import { sleep } from '@/infrastructure/Threading/AsyncSleep'; describe('AsyncLazy', () => { it('returns value from lambda', async () => { @@ -10,7 +10,7 @@ describe('AsyncLazy', () => { const lambda = () => Promise.resolve(expected); const sut = new AsyncLazy(lambda); // act - const actual = await sut.getValueAsync(); + const actual = await sut.getValue(); // assert expect(actual).to.equal(expected); }); @@ -26,7 +26,7 @@ describe('AsyncLazy', () => { }); const results = new Array(); for (let i = 0; i < 5; i++) { - results.push(await sut.getValueAsync()); + results.push(await sut.getValue()); } // assert expect(totalExecuted).to.equal(1); @@ -35,16 +35,16 @@ describe('AsyncLazy', () => { it('when running long-running task in parallel', async () => { // act const sut = new AsyncLazy(async () => { - await sleepAsync(100); + await sleep(100); totalExecuted++; return Promise.resolve(totalExecuted); }); const results = await Promise.all([ - sut.getValueAsync(), - sut.getValueAsync(), - sut.getValueAsync(), - sut.getValueAsync(), - sut.getValueAsync()]); + sut.getValue(), + sut.getValue(), + sut.getValue(), + sut.getValue(), + sut.getValue()]); // assert expect(totalExecuted).to.equal(1); expect(results).to.deep.equal([1, 1, 1, 1, 1]); diff --git a/tests/unit/infrastructure/Threading/AsyncSleep.spec.ts b/tests/unit/infrastructure/Threading/AsyncSleep.spec.ts index 9172bd71..9d87f471 100644 --- a/tests/unit/infrastructure/Threading/AsyncSleep.spec.ts +++ b/tests/unit/infrastructure/Threading/AsyncSleep.spec.ts @@ -1,33 +1,35 @@ import 'mocha'; import { expect } from 'chai'; -import { sleepAsync, SchedulerType } from '@/infrastructure/Threading/AsyncSleep'; +import { sleep, SchedulerType } from '@/infrastructure/Threading/AsyncSleep'; describe('AsyncSleep', () => { - it('fulfills after delay', async () => { - // arrange - const delayInMs = 10; - const scheduler = new SchedulerMock(); - // act - const sleep = sleepAsync(delayInMs, scheduler.mock); - const promiseState = watchPromiseState(sleep); - scheduler.tickNext(delayInMs); - await flushPromiseResolutionQueue(); - // assert - const actual = promiseState.isFulfilled(); - expect(actual).to.equal(true); - }); - it('pending before delay', async () => { - // arrange - const delayInMs = 10; - const scheduler = new SchedulerMock(); - // act - const sleep = sleepAsync(delayInMs, scheduler.mock); - const promiseState = watchPromiseState(sleep); - scheduler.tickNext(delayInMs / 5); - await flushPromiseResolutionQueue(); - // assert - const actual = promiseState.isPending(); - expect(actual).to.equal(true); + describe('sleep', () => { + it('fulfills after delay', async () => { + // arrange + const delayInMs = 10; + const scheduler = new SchedulerMock(); + // act + const promise = sleep(delayInMs, scheduler.mock); + const promiseState = watchPromiseState(promise); + scheduler.tickNext(delayInMs); + await flushPromiseResolutionQueue(); + // assert + const actual = promiseState.isFulfilled(); + expect(actual).to.equal(true); + }); + it('pending before delay', async () => { + // arrange + const delayInMs = 10; + const scheduler = new SchedulerMock(); + // act + const promise = sleep(delayInMs, scheduler.mock); + const promiseState = watchPromiseState(promise); + scheduler.tickNext(delayInMs / 5); + await flushPromiseResolutionQueue(); + // assert + const actual = promiseState.isPending(); + expect(actual).to.equal(true); + }); }); });