Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created March 30, 2020 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrysahaidak/b79607da2d0164ea78113832ae3dd693 to your computer and use it in GitHub Desktop.
Save terrysahaidak/b79607da2d0164ea78113832ae3dd693 to your computer and use it in GitHub Desktop.
Promise Sequence
class Task {
constructor({ id, thunk }) {
this.id = id;
this.thunk = thunk;
this._done = false;
}
setDone() {
this._done = true;
}
}
class Sequence {
constructor(tasks) {
this._tasks = tasks;
}
_stillExist(task) {
const index = this._tasks.findIndex(i => i.id === task.id);
return index > -1;
}
async run() {
const arr = [...this._tasks];
for (let task of arr) {
if (!this._stillExist(task)) {
continue;
}
try {
const res = await task.thunk();
task.setDone();
console.log(res);
} catch (err) {
console.log(err);
}
}
}
removeById(id) {
const index = this._tasks.findIndex(i => i.id === id);
if (index > -1) {
this._tasks.splice(index, 1);
} else {
console.warn(`Task with id ${id} doesn't exists`);
}
}
}
const createThunk = (index) => () => new Promise((res) => {
setTimeout(() => {
res(index);
}, 100);
});
// just generates some array with tasks
// each task should have unique id and thunk - function which returns a promise
const pArray = [...Array(10).keys()].map((index) => {
return new Task({ id: index, thunk: createThunk(index) })
});
const sequence = new Sequence(pArray);
// you can run it
sequence.run()
.then(() => console.log('done'));
// pass an id to remove
sequence.removeById(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment