JSFiddle - React, Tailwind, and code Playground
JavaScript
Promise.resolve().then(_ => console.log("then"));
class Publisher {
constructor() {
this.subscribers = new Set();
}
subscribe(f) {
this.subscribers.add(f);
}
trigger() {
const exceptions = [];
const event = {cancel: false};
for (const f of this.subscribers) {
try {
f(event);
} catch (e) {
exceptions.push(e);
}
if (event.cancel) {
break;
}
}
for (const e of exceptions) {
setTimeout(_ => { throw e; }, 0);
}
}
}
const target = new Publisher();
target.subscribe(e => {
console.log("1");
throw 1;
});
target.subscribe(e => {
console.log("2; cancelling");
e.cancel = true;
throw 2;
});
target.subscribe(e => {
console.log("3");
throw 3;
});
target.trigger();
console.log("dispatch complete");