Created
November 23, 2016 01:02
-
-
Save mgtitimoli/eccbcc3bdda6d327b7f95427ec9d8363 to your computer and use it in GitHub Desktop.
Async Queue
This file contains hidden or 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
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]; | |
} | |
} | |
} |
This file contains hidden or 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
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