Skip to content

Instantly share code, notes, and snippets.

@intech
Created May 16, 2022 08:33
Show Gist options
  • Save intech/13fa92f7cbcb0f006b175ddd631b4a4b to your computer and use it in GitHub Desktop.
Save intech/13fa92f7cbcb0f006b175ddd631b4a4b to your computer and use it in GitHub Desktop.
const StateMachine = require("fsm-async");
const chalk = require("chalk");
class Semaphore extends StateMachine {
constructor() {
const transitionTable = {
initial: "init",
transitions: [
{ ev: "init", from: "init", to: "red" },
{ ev: "_red", from: "red", to: "fromRed" },
{ ev: "toGreen", from: "fromRed", to: "green" },
{ ev: "_green", from: "green", to: "fromGreen" },
{ ev: "toRed", from: "fromGreen", to: "red" }
]
};
super(transitionTable);
this.counter = 0;
}
async _onRed() {
if (this.counter) process.exit();
}
async onGreen() {
console.log(`${chalk.bgGreen.bold("onGreen")}`);
// Instead of really disconnecting we simulate it here
await new Promise(resolve => setTimeout(resolve, 2000));
this._green();
}
async onFromRed() {
console.log(`${chalk.bgYellow.bold("onFromRed")}`, this.getState());
await new Promise(resolve => setTimeout(resolve, 1000));
this.toGreen();
}
async onFromGreen() {
console.log(`${chalk.bgYellow.bold("onFromGreen")}`, this.getState());
await new Promise(resolve => setTimeout(resolve, 1000));
this.toRed();
}
async onRed() {
console.log(`${chalk.bgRed.bold("onRed")}`);
// Instead of really connecting we simulate it here
await new Promise(resolve => setTimeout(resolve, 5000));
this._red();
this.counter++;
}
}
module.exports = Semaphore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment