如何在Node.js中取消一个HTTP请求
5 min read
5分钟阅读
If you’re making an HTTP request in Node.js there’s a good chance you’ll want to cancel it if it takes too long to receive a response. Or perhaps you have a slightly more complex situation where you’re making multiple requests in parallel, and if one request fails you want to cancel all of them. These sound like reasonable things to want to do, but solving these problems is often much less straightforward. You might even end up with a hacky workaround involving setTimeout()
(it’s ok, I’ve been there too!).
如果你在Node.js中做一个HTTP请求,很有可能你会想取消它,如果它需要太长的时间来接收响应。或者,你有一个稍微复杂的情况,你正在平行地发出多个请求,如果一个请求失败,你想取消所有的请求。这些听起来都是合理的事情,但解决这些问题往往不那么简单。你甚至可能最终采用一个涉及setTimeout()
的黑客解决方法(没关系,我也经历过这种情况!)。
Fortunately there’s a JavaScript API which gives us a standard way to cancel asynchronous tasks such as an in-flight HTTP request: the Abort API. This small but powerful API has been available in some web browsers since 2017, and now it’s available in Node.js too. Let’s take a look at what the Abort API is, how it works, and how we can use it to cancel an HTTP request in Node.js.
幸运的是,有一个JavaScript API为我们提供了取消异步任务的标准方法,如飞行中的HTTP请求:Abort API。这个小而强大的API自2017年以来一直在一些Web浏览器中可用,现在它在Node.js中也可用。让我们来看看Abort API是什么,它是如何工作的,以及我们如何使用它来取消Node.js中的HTTP请求。
The Abort API is a JavaScript API which consists of two classes: AbortController
and AbortSignal
. Here’s an example of them in action:
Abort API是一个JavaScript API,由两个类组成:AbortController
和AbortSignal
。下面是它们的一个操作例子。
const controller = new AbortController();
const signal = controller.signal; signal.addEventListener("abort", () => { console.log("The abort signal was triggered");
}, { once: true }); controller.abort();
When the controller.abort()
method is called, it sets the signal’s aborted
property to true
. It also dispatches an abort
event from the AbortSignal
instance in controller.signal
to the list of registered handlers. In the example above we’ve registered one handler for the abort
event type, which logs a message to let us know that the abort signal was triggered. If you’re usi...