Skip to content

Instantly share code, notes, and snippets.

@Deepak13245
Created June 2, 2020 20:43
Show Gist options
  • Save Deepak13245/8e2653f6a298e3aef67227816d18dbbb to your computer and use it in GitHub Desktop.
Save Deepak13245/8e2653f6a298e3aef67227816d18dbbb to your computer and use it in GitHub Desktop.
Worker implementation for async functions
class Worker {
_stopped = false;
_started = false;
_onStop = noOp;
constructor(channel, fn) {
this._channel = channel;
this._fn = fn;
}
setOnStop(cb) {
this._onStop = cb;
}
async start() {
if(this._started) {
return;
}
this._stopped = false;
while(!this._stopped) {
const [exists, item, callback] = this._channel.next();
if(!exists) {
this._started = false;
this._onStop(this);
return;
}
try {
callback({
status: true,
result: await this._fn(...item)
});
} catch(error) {
callback({
status: false,
result: error,
});
}
}
}
stop() {
this._stopped = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment