Context in JavaScript
Here’s the translation of the Go code to JavaScript, formatted in Markdown 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 operations and cancellation in JavaScript. We’ll use the express
framework for creating the server and node-abort-controller
for handling cancellation.
First, let’s set up our dependencies:
Now, let’s define our request handler:
In this handler:
- We create an
AbortController
for each request. This is similar to thecontext.Context
in the original example. - We use
setTimeout
to simulate a long-running operation. - We listen for the ‘close’ event on the request, which is emitted when the client disconnects.
- We use the
AbortSignal
to handle cancellation, similar to howctx.Done()
is used in the original.
Now, let’s set up our server:
To run this server:
You can then simulate a client request to /hello
, and interrupt it:
In this JavaScript version, we’ve replicated the behavior of the original Go example using Express and AbortController. The AbortController
provides similar functionality to Go’s context.Context
, allowing us to handle cancellation in a clean way.
Note that JavaScript’s asynchronous nature and event-driven model provide a different approach to handling concurrency compared to Go’s goroutines, but the end result is similar.