Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: frontend: Add one-more-time #2430

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 63 additions & 0 deletions core/frontend/src/one-more-time.ts
@@ -0,0 +1,63 @@
/**
* After multiple years and attempts
* This is a RAII class that takes advantage of the new disposable feature
* to create a promise that repeats itself until it's disposed
*/
class OneMoreTime {
private isDisposed = false

constructor(
private readonly action: () => Promise<void>,
private readonly timeout = 5000,
autostart = true,
) {
// One more time
if (autostart) {
// eslint-disable-next-line no-return-await
(async () => await this.start())()
}
}

async start(): Promise<void> {
// Come on, alright
if (this.isDisposed) return

try {
// One more time, we're gonna celebrate
await this.action()
} catch (error) {
console.error('Error in self-calling promise:', error)
// Oh yeah, alright, don't stop the dancing
// eslint-disable-next-line no-promise-executor-return
await new Promise((resolve) => setTimeout(resolve, this.timeout))
}

// One more time, a celebration
// eslint-disable-next-line no-return-await
(async () => await this.start())()
}

// Celebrate and dance so free
[Symbol.dispose](): void {
this.stop()
}

// Stop timer
stop(): void {
this.isDisposed = true
}
}

/** Example
async function logTimestamp() {
console.log('Current timestamp:', new Date())
await new Promise(resolve => setTimeout(resolve, 1000)) // Simulate some async work
}

(async () => {
console.log("started")
using task = new OneMoreTime(logTimestamp)
await new Promise(resolve => setTimeout(resolve, 5000)) // Simulate some async work
console.log("done")
})()
*/