@@ -136,19 +136,62 @@ For more details, see the [MCP Cancellation Documentation](https://modelcontextp
136136Not everyone is familiar with signals and the ` AbortController ` API. Here's a simple example to illustrate how it works:
137137
138138``` js
139+ const { spawn } = require (' child_process' )
139140const controller = new AbortController ()
140141const signal = controller .signal
141142
143+ // Track the child process that needs cleanup
144+ let childProcess = null
145+
146+ // Add an event listener to the signal - this is crucial for cleanup!
147+ signal .addEventListener (' abort' , () => {
148+ console .log (' Signal was aborted! Killing child process...' )
149+ if (childProcess) {
150+ childProcess .kill (' SIGTERM' )
151+ childProcess = null
152+ console .log (' Child process killed' )
153+ }
154+ })
155+
142156async function doLongTask (signal ) {
143- for (let i = 0 ; i < 10 ; i++ ) {
144- if (signal .aborted ) {
145- throw new Error (' Operation cancelled' )
157+ // Start a child process that processes data
158+ childProcess = spawn (' data-processor' , [' --input' , ' large-dataset.csv' , ' --output' , ' processed-data.json' ], {
159+ stdio: [' pipe' , ' pipe' , ' pipe' ]
160+ })
161+
162+ try {
163+ // Listen to the child process output
164+ childProcess .stdout .on (' data' , (data ) => {
165+ const output = data .toString ().trim ()
166+ console .log (' Child output:' , output)
167+
168+ if (output .includes (' Processing complete!' )) {
169+ console .log (' All items processed successfully!' )
170+ }
171+ })
172+
173+ // Wait for the child process to complete
174+ await new Promise ((resolve , reject ) => {
175+ childProcess .on (' close' , (code ) => {
176+ if (code === 0 ) {
177+ resolve (' Processing completed successfully' )
178+ } else {
179+ reject (new Error (\` Child process exited with code \$ {code}\` ` ))
180+ }
181+ })
182+
183+ childProcess .on (' error' , reject)
184+ })
185+
186+ return ' Done!'
187+ } finally {
188+ // Clean up child process when task completes normally
189+ if (childProcess) {
190+ childProcess .kill (' SIGTERM' )
191+ childProcess = null
192+ console .log (' Child process cleaned up normally' )
146193 }
147- // Simulate work
148- await new Promise ((r ) => setTimeout (r, 500 ))
149- console .log (` Step ${ i + 1 } complete` )
150194 }
151- return ' Done!'
152195}
153196
154197doLongTask (signal)
0 commit comments