Last active
March 14, 2019 07:27
-
-
Save DimitryDushkin/a5de02adebf963e770fbe93e194e30b3 to your computer and use it in GitHub Desktop.
Helpful wrapper to make sure that function body is working once per multiple calls
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
export const SINGLE_TASK_BLOCKED = Symbol('task blocked'); | |
export type SingleTaskBlocked = typeof SINGLE_TASK_BLOCKED; | |
export const singleTaskQueue = <TReturn, TArgs extends Array<any>>(func: (...args: TArgs) => Promise<TReturn>) => { | |
let isWorking = false; | |
return async (...args: TArgs): Promise<TReturn | SingleTaskBlocked> => { | |
if (isWorking) { | |
return SINGLE_TASK_BLOCKED; | |
} | |
isWorking = true; | |
const result = await func(...args); | |
isWorking = false; | |
return result; | |
}; | |
}; | |
// Example as test | |
test('singleTaskQueue works as expected with heavy function', async () => { | |
const sumSingleTaskQueued = singleTaskQueue(async () => { | |
await pause(50); | |
return 'result'; | |
}); | |
const expectedResult = 'result'; | |
const result = sumSingleTaskQueued(); | |
const resultBlocked = sumSingleTaskQueued(); | |
expect(await result).toEqual(expectedResult); | |
expect(await resultBlocked).toEqual(SINGLE_TASK_BLOCKED); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment