Using AbortSignal with Node.js

Posted by

Aborting fetch requests with AbortSignal in Node.js

Aborting fetch requests with AbortSignal in Node.js

Node.js has introduced AbortSignal to allow for the cancellation of asynchronous operations, such as fetch requests. This feature provides a way to stop the execution of an asynchronous operation if it’s no longer needed, reducing unnecessary load on the server and improving performance.

Using AbortSignal with fetch requests

To use AbortSignal with fetch requests in Node.js, you need to create a new AbortController and pass its signal property to the fetch request. Here’s an example:


const { AbortController } = require('abort-controller');

const controller = new AbortController();
const signal = controller.signal;

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data', { signal });
    const data = await response.json();
    console.log(data);
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Fetch request was aborted');
    } else {
      console.error('An error occurred', error);
    }
  }
};

// Start the fetch request
fetchData();

// Abort the fetch request after 5 seconds
setTimeout(() => {
  controller.abort();
}, 5000);

In this example, we create a new AbortController and obtain its signal property. We then pass this signal to the fetch request as an option. We also define an asynchronous function fetchData, which makes the fetch request and processes the response. We use a try-catch block to handle the abort error when the fetch request is aborted. Finally, we start the fetch request and abort it after 5 seconds.

Benefits of using AbortSignal

Using AbortSignal with fetch requests in Node.js offers several benefits:

  • Allows for the cancellation of unnecessary fetch requests, reducing server load and improving performance
  • Provides a more efficient way to manage asynchronous operations and handle user interactions, such as canceling a pending request when the user navigates to a different page
  • Improves the overall reliability and responsiveness of the application by avoiding unnecessary network requests

Conclusion

AbortSignal in Node.js provides a powerful way to cancel fetch requests and other asynchronous operations, improving the efficiency and reliability of applications. By taking advantage of this feature, developers can build more responsive and performant Node.js applications.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@JMNinja-od9iz
9 months ago

+1 pour le tip `AbortSignal.timeout()` : beaucoup plus pratique que d'utiliser un timer manuel./ Je retiens ! Merci 😉

@robloxstudiofr2344
9 months ago

C'est just parfait!