Workers - Directly import `waitUntil` in Workers for easily spawning background tasks
11mo ago
Source
CloudflareWorkers - Directly import `waitUntil` in Workers for easily spawning background taskscloudflare.comYou can now import waitUntil from cloudflare:workers to extend your Worker's execution beyond the request lifecycle from anywhere in your code. Previously, waitUntil could only be accessed through the execution context ( ctx ) parameter passed to your Worker's handler functions. This meant that if you needed to schedule background tasks from deeply nested functions or utility modules, you had to pass the ctx object through multiple function calls to access waitUntil . Now, you can import waitUntil directly and use it anywhere in your Worker without needing to pass ctx as a parameter: import { waitUntil } from "cloudflare:workers" ; export function trackAnalytics ( eventData ) { const analyticsPromise = fetch ( " , { method : "POST" , body : JSON . stringify ( eventData ) , } ) ; // Extend execution to ensure analytics tracking completes waitUntil ( analyticsPromise ) ; } This is particularly useful when you want to: Schedule background tasks from utility functions or modules Extend execution for analytics, logging, or cleanup operations Avoid passing the execution context through multiple layers of function calls import { waitUntil } from "cloudflare:workers" ; export default { async fetch ( request , env , ctx ) { // Background task that should complete even after response is sent cleanupTempData ( env . KV_NAMESPACE ) ; return new Response ( "Hello, World!" ) ; } }; function cleanupTempData ( kvNamespace ) { // This function can now use waitUntil without needing ctx const deletePromise = kvNamespace . delete ( "temp-key" ) ; waitUntil ( deletePromise ) ; } Note The imported waitUntil function works the same way as ctx.waitUntil() . It extends your Worker's execution to wait for the provided promise to settle, but does not block the response from being sent to the client. For more information, see the waitUntil documentation .
You might also wanna read
Cloudflare expands AI bot management tools with granular traffic controls for all customers
Cloudflare is celebrating the second "Content Independence Day" by expanding AI traffic management options for all website owners. Building
Workers - Simpler runtime types with @cloudflare/workers-types v5
Cloudflare·1d ago
AI Search - Manage AI Search sync jobs with Wrangler CLI
Cloudflare·2d ago
Workers - Work across multiple accounts with Wrangler auth profiles
Cloudflare·2d ago
Cache - Cache multiple versions of a URL with Vary
Cloudflare·2d ago
Cloudflare One - Hostname routing for Cloudflare Mesh
Cloudflare·2d ago

Comments
Sign in to join the conversation.
No comments yet. Be the first.