Created
June 2, 2020 20:43
-
-
Save Deepak13245/8e2653f6a298e3aef67227816d18dbbb to your computer and use it in GitHub Desktop.
Worker implementation for async functions
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 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