Cancelling in-progress network operations is critical for applications to maintain responsiveness and avoid doing work that isn’t needed anymore. There are many situations where you want to cancel on-going work, for example when you are:

  • downloading a large file from Azure Storage and the user wants to cancel the download
  • processing events from an Event Hub and you need to gracefully shut down in order to scale down or to apply updates
  • running an operation that might take a while and you don’t want to wait longer than a fixed amount of time
  • running multiple operations in parallel and getting one result makes the other results irrelevant

The new Azure SDK libraries for JavaScript and TypeScript have adopted abort signals situations like these.

AbortController & AbortSignal

AbortController and AbortSignal are standard features in the browser and are used with the fetch API to abort in-progress network requests. The controller is responsible for triggering the cancellation, and signals are responsible for notifying when a cancellation has been triggered. This separation of concerns enables you to safely pass the abort signal to other parts of your application without worrying about it unintentionally cancelling the request.

If you’re only targeting fairly modern browsers, you can use the built-in AbortController and AbortSignal and everything will work fine. If you’re targeting Node.js, or if you want to take advantage of linked signals or other features that I’ll cover later in this post, you can use the implementation in the Azure SDK found in the @azure/abort-controller npm package.

To abort an in-progress request such as an upload or download in storage, create a new AbortController and pass its signal into the method you might want to cancel later:

// Omit this line if you want to use the AbortSignal built into the browser.
import { AbortController } from "@azure/abort-controller";

// create a controller and get its signal
const controller = new AbortController();
const abortSignal = controller.signal;

// pass the abortSignal into the API you want to cancel
await blobClient.download({ abortSignal })

// then sometime later, cancel it!
controller.abort();

Note that cancelling using AbortController only affects client-side code. It does not notify the service that cancellation has happened. For example, if you are uploading a key into Key Vault and you cancel before it finishes, the key might still be created.

#azure sdk #javascript #programming #typescript

How to cancel operations in the Azure SDK for JavaScript/TypeScript
3.15 GEEK