Trying to write the flow logic for a drawing tool where user can enter keyboard input to draw on a cavas let’s say, to achieve this I’m trying to chain event listeners in a way that they remove themselves once done. I would rather do this than keeping track of a global state that manages which listeners are active etc. I’m making progress but I’m stuck on recusive calls to Promise.race
not sure if there’s a better way to achieve this.
Using Promise.race in a recusive loop means that alot of the promises do not get resolved.
Is there a better way for me to do this?
export function startCount(node) {
const counter = Object.create(counterMethods);
counter.node = node;
counter.number = 0;
counter.exitloopflag = false;
return counter;
}
const counterMethods = {
doCounter: function () {
return new Promise((resolve) => {
let handler = () => {
console.log("click");
this.node.removeEventListener("click", handler);
resolve();
};
this.node.addEventListener("click", handler);
});
},
quit: function () {
return new Promise((resolve) => {
let handler = (e) => {
if (e.key === "Escape") {
this.node.removeEventListener("keydown", handler);
resolve("exit");
}
};
this.node.addEventListener("keydown", handler);
});
},
counterFlow: function () {
if (this.exit) return;
Promise.race([this.doCounter(), this.quit()]).then((value) => { //<-- not confident about this
console.log(`The value is !!!: ${value}`);
if (value === "exit") {
this.exit = true;
} else {
this.number += 1;
console.log(`you have clicked ${this.number} times`);
this.counterFlow(); //<-- recursive call, means I'm leaving a lot of unresolved promises.
}
});
},
};
let obj = new startCount(document);
obj.counterFlow();