Created
January 17, 2024 23:03
-
-
Save alxgrk/92e982672a17aa7dd7aed987f6906ed8 to your computer and use it in GitHub Desktop.
AbortController in Express.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const app = express(); | |
console.log("initializing") | |
app.get("/foo", (req, res) => { | |
const abort = new AbortController() | |
console.log("entered /foo") | |
req.on('end', () => { | |
// this is only called when the request successfully sent a response | |
console.log("ended"); | |
}); | |
req.on('close', () => { | |
// this is called everytime the request ends - no matter | |
// whether a response was sent successfully or not | |
abort.abort(); | |
console.log("closed"); | |
}); | |
const timeout = setTimeout(() => { | |
console.log("Completed") | |
res.sendStatus(200); | |
}, 2000); | |
abort.signal.onabort = () => { | |
// this clears the timeout, so if the client cancels the request within | |
// the 2 seconds of `setTimeout`, `Completed` will not be printed | |
console.log("aborted") | |
clearTimeout(timeout); | |
}; | |
}); | |
app.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
$ node express-abort.js
Sequence of log output: