winterspec
Version:
Write Winter-CG compatible routes with filesystem routing and tons of features
39 lines (38 loc) • 1.18 kB
JavaScript
import EventEmitter from "node:events";
/**
* This is effectively a Promise that can be resolved multiple times in different scopes without messily holding references to the resolve function.
*/
export class AsyncWorkTracker extends EventEmitter {
constructor() {
super(...arguments);
this.state = "idle";
}
/**
* If work is still pending, this waits for the next work result. If work is already resolved, it returns the last result.
*/
async waitForResult() {
if (this.state === "pending" || !this.lastResult) {
return new Promise((resolve) => {
this.once("result", resolve);
});
}
if (!this.lastResult) {
throw new Error("No last result (this should never happen)");
}
return this.lastResult;
}
/**
* Call this when you start async work.
*/
beginAsyncWork() {
this.state = "pending";
}
/**
* Call this when the async work is done with the result.
*/
finishAsyncWork(result) {
this.state = "resolved";
this.emit("result", result);
this.lastResult = result;
}
}