lik/ts/lik.asyncexecutionstack.ts

25 lines
796 B
TypeScript
Raw Normal View History

2023-01-18 11:18:47 +00:00
import * as plugins from './lik.plugins.js'
/**
* allows for avoiding race condition
*/
export class AsyncExecutionStack {
public currentExecutions: Promise<any>[] = [];
public async getExclusiveExecutionSlot(funcArg: () => Promise<any>, timeoutArg: number) {
const executionDeferred = plugins.smartpromise.defer();
this.currentExecutions.push(executionDeferred.promise);
for (const promiseArg of this.currentExecutions) {
if (promiseArg !== executionDeferred.promise) {
await promiseArg;
} else {
if (timeoutArg) {
await Promise.race([funcArg(),plugins.smartdelay.delayFor(timeoutArg)])
} else {
await funcArg();
}
executionDeferred.resolve();
this.currentExecutions.shift();
}
}
};
}