Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Created November 23, 2016 01:02
Show Gist options
  • Save mgtitimoli/eccbcc3bdda6d327b7f95427ec9d8363 to your computer and use it in GitHub Desktop.
Save mgtitimoli/eccbcc3bdda6d327b7f95427ec9d8363 to your computer and use it in GitHub Desktop.
Async Queue
import createCancellationToken from './createCancellationToken';
export default class AsyncQueue {
process = createCancellationToken()
_tasks = [];
enqueue(...newTasks) {
this._tasks.push(...newTasks);
return this;
}
flush() {
this.process.cancel();
this._tasks.splice(0, this._tasks.length);
return this;
}
async run() {
let prevResult;
let task = this._tasks[0];
this.process = createCancellationToken();
while (!this.process.isCancelled() && task) {
prevResult = await task(this.process, prevResult);
this._tasks.shift();
task = this._tasks[0];
}
}
}
const createCancellationToken = () => {
let cancelled = false;
return {
isCancelled() {
return cancelled;
},
cancel() {
cancelled = true;
},
};
};
export default createCancellationToken;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment