Kay
Kay•10mo ago

Make deno.serve handler asynchronous

How can i make the Deno.serve handler asynchronous? or like make it so that it can execute asynchronous functions
1 Reply
Deno AI Helper
Deno AI Helper•10mo ago
To make the Deno.serve handler asynchronous, you can define your handler function as an async function. This allows you to use await within the handler to execute asynchronous functions. Here's an example from the documentation:
Deno.serve(async (req) => {
// You can perform asynchronous operations here
const body = await req.text();
console.log("Body:", body);

// Return a response
return new Response("Hello, World!");
});
Deno.serve(async (req) => {
// You can perform asynchronous operations here
const body = await req.text();
console.log("Body:", body);

// Return a response
return new Response("Hello, World!");
});
In this example, the handler function is marked as async, which means it can contain asynchronous code using await. The req.text() method is an asynchronous operation that reads the request body and returns it as a string. By awaiting this operation, the function execution pauses until the promise returned by req.text() is resolved. Remember that when you define your handler as an async function, it implicitly returns a promise, even if you return a Response object directly. The Deno.serve function is designed to handle this, so it will wait for the promise to resolve before sending the response back to the client. 🦕