Created
March 30, 2020 09:40
-
-
Save terrysahaidak/b79607da2d0164ea78113832ae3dd693 to your computer and use it in GitHub Desktop.
Promise Sequence
This file contains 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 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