Files
taskbuffer/ts/taskbuffer.classes.taskchain.ts

70 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2017-06-17 16:56:33 +02:00
// TaskChain chains tasks
// and extends Task
2022-03-25 12:14:49 +01:00
import * as plugins from './taskbuffer.plugins.js';
import { Task } from './taskbuffer.classes.task.js';
import { logger } from './taskbuffer.logging.js';
2016-05-05 19:21:01 +02:00
export class Taskchain extends Task {
2018-08-04 17:53:22 +02:00
taskArray: Task[];
2017-02-15 22:52:29 +01:00
constructor(optionsArg: {
2018-08-04 17:53:22 +02:00
taskArray: Task[];
name?: string;
log?: boolean;
buffered?: boolean;
bufferMax?: number;
2017-02-15 22:52:29 +01:00
}) {
2020-07-12 00:48:51 +00:00
const options = {
2018-08-04 17:53:22 +02:00
...{
2017-02-15 22:52:29 +01:00
name: 'unnamed Taskchain',
2020-07-12 00:48:51 +00:00
log: false,
2017-02-15 22:52:29 +01:00
},
2018-08-04 17:53:22 +02:00
...optionsArg,
...{
taskFunction: (x: any) => {
// this is the function that gets executed when TaskChain is triggered
2020-07-12 00:48:51 +00:00
const done = plugins.smartpromise.defer(); // this is the starting Deferred object
2018-08-04 17:53:22 +02:00
let taskCounter = 0; // counter for iterating async over the taskArray
2021-09-26 14:45:02 +02:00
const iterateTasks = (x: any) => {
2018-08-04 17:53:22 +02:00
if (typeof this.taskArray[taskCounter] !== 'undefined') {
logger.log('info', `${this.name} running: Task ${this.taskArray[taskCounter].name}`);
2020-07-12 00:48:51 +00:00
this.taskArray[taskCounter].trigger(x).then((x) => {
logger.log('info', this.taskArray[taskCounter].name);
2018-08-04 17:53:22 +02:00
taskCounter++;
iterateTasks(x);
}).catch((err) => {
const chainError = new Error(
`Taskchain "${this.name}": task "${this.taskArray[taskCounter].name || 'unnamed'}" (index ${taskCounter}) failed: ${err instanceof Error ? err.message : String(err)}`
);
(chainError as any).cause = err;
done.reject(chainError);
2018-08-04 17:53:22 +02:00
});
2017-02-15 22:52:29 +01:00
} else {
logger.log('info', `Taskchain "${this.name}" completed successfully`);
2018-08-04 17:53:22 +02:00
done.resolve(x);
}
2018-08-04 17:53:22 +02:00
};
iterateTasks(x);
return done.promise;
2020-07-12 00:48:51 +00:00
},
},
2018-08-04 17:53:22 +02:00
};
super(options);
this.taskArray = optionsArg.taskArray;
2017-02-15 22:52:29 +01:00
}
2018-08-04 17:53:22 +02:00
addTask(taskArg: Task) {
this.taskArray.push(taskArg);
2017-06-09 23:33:41 +02:00
}
removeTask(taskArg: Task): boolean {
const index = this.taskArray.indexOf(taskArg);
if (index === -1) {
return false;
}
this.taskArray.splice(index, 1);
return true;
2017-06-09 23:33:41 +02:00
}
shiftTask(): Task | undefined {
return this.taskArray.shift();
2017-06-09 23:33:41 +02:00
}
2017-02-15 22:52:29 +01:00
}