From 91562db29bc3fca8a629b82467b9cde0c180acf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20=C4=8Cern=C3=BD?= <112722215+cernymatej@users.noreply.github.com> Date: Thu, 28 Nov 2024 11:00:58 +0100 Subject: [PATCH] docs: add a section about `event.waitUntil` (#29583) --- .../2.guide/2.directory-structure/1.server.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/2.guide/2.directory-structure/1.server.md b/docs/2.guide/2.directory-structure/1.server.md index bb4dc8c8a2..3bd95a592c 100644 --- a/docs/2.guide/2.directory-structure/1.server.md +++ b/docs/2.guide/2.directory-structure/1.server.md @@ -363,6 +363,26 @@ Headers that are **not meant to be forwarded** will **not be included** in the r `transfer-encoding`, `connection`, `keep-alive`, `upgrade`, `expect`, `host`, `accept` :: +### Awaiting Promises After Response + +When handling server requests, you might need to perform asynchronous tasks that shouldn't block the response to the client (for example, caching and logging). You can use `event.waitUntil` to await a promise in the background without delaying the response. + +The `event.waitUntil` method accepts a promise that will be awaited before the handler terminates, ensuring the task is completed even if the server would otherwise terminate the handler right after the response is sent. This integrates with runtime providers to leverage their native capabilities for handling asynchronous operations after the response is sent. + +```ts [server/api/background-task.ts] +const timeConsumingBackgroundTask = async () => { + await new Promise((resolve) => setTimeout(resolve, 1000)) +}; + +export default eventHandler((event) => { + // schedule a background task without blocking the response + event.waitUntil(timeConsumingBackgroundTask()) + + // immediately send the response to the client + return 'done' +}); +``` + ## Advanced Usage ### Nitro Config