Context in TypeScript
Here’s the translation of the Go code to TypeScript, along with explanations in Markdown format suitable for Hugo:
In this example, we’ll look at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of asynchronous programming and cancellation in TypeScript. We’ll use the http
module from Node.js to create our server.
In this TypeScript version:
We import the
http
module from Node.js.The
hello
function simulates a long-running operation usingsetTimeout
. It waits for 10 seconds before sending a response.We use the
req.on('close', ...)
event to handle client disconnection. This is similar to checking the context’sDone()
channel in the original example.The server is created using
http.createServer()
, and we route the ‘/hello’ path to ourhello
function.Finally, we start the server listening on port 8090.
To run the server:
Now, you can simulate a client request to /hello
, and cancel it shortly after starting:
In the server logs, you should see:
This demonstrates how we can handle cancellation in an asynchronous TypeScript server, similar to the context cancellation in the original example.