Last active
May 18, 2023 12:08
-
-
Save asvae/24958c98ecaf771123eff6f15477837c to your computer and use it in GitHub Desktop.
Executor pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Class | |
| export default class Executor { | |
| command: Function | |
| wasLastRunFine: Boolean = false | |
| runCount: Number = 0 // Currently active commands count | |
| wasRun: Boolean = false | |
| wasRunFine: Boolean = false | |
| wasRunBad: Boolean = false | |
| constructor (command: () => Promise) { | |
| this.command = command | |
| } | |
| get isRunning (): Boolean { | |
| return !!this.runCount | |
| } | |
| /** | |
| * @protected | |
| */ | |
| beforeRun (): void { | |
| this.runCount++ | |
| } | |
| /** | |
| * @protected | |
| */ | |
| afterRun (promise: Promise): void { | |
| promise.then(() => { | |
| this.runCount-- | |
| this.setRunResultFlags(true) | |
| }) | |
| promise.catch((result) => { | |
| this.runCount-- | |
| this.setRunResultFlags(false) | |
| }) | |
| } | |
| /** | |
| * @public | |
| */ | |
| run (...parameters): Promise { | |
| this.beforeRun() | |
| const promise = this.command(...parameters) | |
| if (!(promise instanceof Promise)) { | |
| console.error('some') | |
| throw new Error('Executor command should return promise.') | |
| } | |
| this.afterRun(promise) | |
| return promise | |
| } | |
| /** | |
| * @protected | |
| */ | |
| setRunResultFlags (success: Boolean) { | |
| this.wasRun = true | |
| this.wasLastRunFine = success | |
| if (success) { | |
| this.wasRunFine = true | |
| } | |
| if (!success) { | |
| this.wasRunBad = true | |
| } | |
| } | |
| } | |
| // Tests | |
| import Executor from '../../../../src/classes/Ajax/Executor/Executor.js' | |
| describe('Executor', () => { | |
| describe('run', () => { | |
| it('promise closure', (done) => { | |
| let state = 'default' | |
| const executor = new Executor((value) => { | |
| return new Promise((resolve) => { | |
| setTimeout(() => { | |
| state = value | |
| resolve() | |
| done() | |
| expect(state).toBe('changed') | |
| }, 100) | |
| }) | |
| }) | |
| executor.run('changed') | |
| expect(state).toBe('default') | |
| }) | |
| it('counts sequential runs', (done) => { | |
| const executor = new Executor(() => { | |
| return new Promise((resolve) => { | |
| setTimeout(resolve, 100) | |
| }) | |
| }) | |
| Promise.all([ | |
| executor.run(), | |
| executor.run(), | |
| ]).then(() => { | |
| expect(executor.isRunning).toBe(false) | |
| expect(executor.runCount).toBe(0) | |
| done() | |
| }) | |
| expect(executor.isRunning).toBe(true) | |
| expect(executor.runCount).toBe(2) | |
| }) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment