Hasty Briefsbeta

Bilingual

You can't cancel a JavaScript promise (except sometimes you can)

6 hours ago
  • #Control Flow
  • #JavaScript
  • #Async Programming
  • JavaScript promises lack a built-in cancellation method due to potential resource state issues.
  • Interrupting async functions can be done by returning a promise that never resolves, allowing garbage collection to clean up.
  • Using errors for interruption is problematic because try/catch blocks can inadvertently swallow interruption errors.
  • Generators allow clean interruption via yield but require specific syntax and don't handle concurrency well.
  • The technique involves memoizing step results and interrupting after each step, enabling resumption across invocations.
  • A setTimeout of 0 milliseconds ensures microtasks drain before checking for new steps, facilitating step-by-step execution.
  • Memory isn't leaked because unreferenced promises and functions are garbage collected, as demonstrated with FinalizationRegistry.
  • This pattern is used in the Inngest TypeScript SDK for serverless workflows with hard timeouts.