%3CLINGO-SUB%20id%3D%22lingo-sub-1321797%22%20slang%3D%22en-US%22%3EUsing%20Abort%20signals%20to%20cancel%20operations%20in%20the%20Azure%20SDK%20for%20JavaScript%2FTypeScript%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-1321797%22%20slang%3D%22en-US%22%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%20class%3D%22rich-diff-level-zero%22%3ECancelling%20in-progress%20network%20operations%20is%20critical%20for%20applications%20to%20maintain%20responsiveness%20and%20avoid%20doing%20work%20that%20isn't%20needed%20anymore.%20There%20are%20many%20situations%20where%20you%20want%20to%20cancel%20on-going%20work%2C%20for%20example%20when%20you%20are%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CUL%20class%3D%22added%20rich-diff-level-zero%22%3E%0A%3CLI%20class%3D%22rich-diff-level-one%22%3Edownloading%20a%20large%20file%20from%20Azure%20Storage%20and%20the%20user%20wants%20to%20cancel%20the%20download%3C%2FLI%3E%0A%3CLI%20class%3D%22rich-diff-level-one%22%3Eprocessing%20events%20from%20an%20Event%20Hub%20and%20you%20need%20to%20gracefully%20shut%20down%20in%20order%20to%20scale%20down%20or%20to%20apply%20updates%3C%2FLI%3E%0A%3CLI%20class%3D%22rich-diff-level-one%22%3Erunning%20an%20operation%20that%20might%20take%20a%20while%20and%20you%20don't%20want%20to%20wait%20longer%20than%20a%20fixed%20amount%20of%20time%3C%2FLI%3E%0A%3CLI%20class%3D%22rich-diff-level-one%22%3Erunning%20multiple%20operations%20in%20parallel%20and%20getting%20one%20result%20makes%20the%20other%20results%20irrelevant%3C%2FLI%3E%0A%3C%2FUL%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%20class%3D%22rich-diff-level-zero%22%3EThe%20new%20Azure%20SDK%20libraries%20for%20JavaScript%20and%20TypeScript%20have%20adopted%20abort%20signals%20situations%20like%20these.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--1357324236%22%20id%3D%22toc-hId--1357174572%22%3EAbortSignal%20%26amp%3B%20AbortController%3C%2FH2%3E%0A%3CP%3E%3CTT%3EAbortController%3C%2FTT%3E%20and%20%3CTT%3EAbortSignal%3C%2FTT%3E%20are%20%3CA%20href%3D%22https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FAbortController%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3Estandard%20features%20in%20the%20browser%3C%2FA%3E%20and%20are%20used%20with%20the%20%3CA%20href%3D%22https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FWindowOrWorkerGlobalScope%2Ffetch%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3E%3CTT%3Efetch%3C%2FTT%3E%20API%3C%2FA%3E%20to%20abort%20in-progress%20network%20requests.%20The%20controller%20is%20responsible%20for%20triggering%20the%20cancellation%2C%20and%20signals%20are%20responsible%20for%20notifying%20when%20a%20cancellation%20has%20been%20triggered.%20This%20separation%20of%20concerns%20enables%20you%20to%20safely%20pass%20the%20abort%20signal%20to%20other%20parts%20of%20your%20application%20without%20worrying%20about%20it%20unintentionally%20cancelling%20the%20request.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIf%20you're%20only%20targeting%20fairly%20modern%20browsers%2C%20you%20can%20use%20the%20built-in%20%3CTT%3EAbortController%3C%2FTT%3E%20and%20%3CTT%3EAbortSignal%3C%2FTT%3E%20and%20everything%20will%20work%20fine.%20If%20you're%20targeting%20Node.js%2C%20or%20if%20you%20want%20to%20take%20advantage%20of%20linked%20signals%20or%20other%20features%20that%20I'll%20cover%20later%20in%20this%20post%2C%20you%20can%20use%20the%20implementation%20in%20the%20Azure%20SDK%2C%20found%20in%20the%20%3CA%20href%3D%22https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40azure%2Fabort-controller%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3E%3CTT%3E%40azure%2Fabort-controller%3C%2FTT%3E%20npm%20package%3C%2FA%3E.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20abort%20an%20in-progress%20request%20such%20as%20an%20upload%20or%20download%20in%20storage%2C%20create%20a%20new%20%3CTT%3EAbortController%3C%2FTT%3E%20and%20pass%20its%20signal%20into%20the%20method%20you%20might%20want%20to%20cancel%20later%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3E%2F%2F%20Omit%20this%20line%20if%20you%20want%20to%20use%20the%20AbortSignal%20built%20into%20the%20browser.%0Aimport%20%7B%20AbortController%20%7D%20from%20%22%40azure%2Fabort-controller%22%3B%0A%0A%2F%2F%20create%20a%20controller%20and%20get%20its%20signal%0Aconst%20controller%20%3D%20new%20AbortController()%3B%0Aconst%20abortSignal%20%3D%20controller.signal%3B%0A%0A%2F%2F%20pass%20the%20abortSignal%20into%20the%20API%20you%20want%20to%20cancel%0Aawait%20blobClient.download(%7B%20abortSignal%20%7D)%0A%0A%2F%2F%20then%20sometime%20later%2C%20cancel%20it!%0Acontroller.abort()%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ENote%20that%20cancelling%20using%20%3CTT%3EAbortController%3C%2FTT%3E%20only%20affects%20client-side%20code.%20It%20does%20not%20notify%20the%20service%20that%20cancellation%20has%20happened.%20For%20example%2C%20if%20you%20are%20uploading%20a%20key%20into%20Key%20Vault%20and%20you%20cancel%20before%20it%20finishes%2C%20the%20key%20might%20still%20be%20created.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-1130188597%22%20id%3D%22toc-hId-1130338261%22%3ECancelling%20multiple%20operations%3C%2FH2%3E%0A%3CP%3EOften%20you%20have%20multiple%20in-flight%20operations%20that%20you%20might%20want%20to%20cancel%20all%20at%20once.%20To%20continue%20our%20Storage%20example%2C%20maybe%20you're%20downloading%20multiple%20files%20in%20parallel.%20Or%2C%20perhaps%20you%20have%20to%20fetch%20a%20secret%20from%20Azure%20Key%20Vault%20before%20using%20that%20secret%20in%20a%20subsequent%20operation.%20In%20that%20case%2C%20you%20can%20pass%20the%20same%20signal%20to%20each%20method%2C%20and%20calling%20abort%20on%20the%20controller%20will%20cancel%20whichever%20of%20them%20is%20in%20progress%20at%20that%20time.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3Easync%20function%20getShoppingList(%7B%20abortSignal%20%7D)%20%7B%0A%20%20%20%20const%20cs%20%3D%20await%20secretClient.getSecret('storage-connection-string'%2C%20%7B%20abortSignal%20%7D)%3B%0A%20%20%20%20const%20blobClient%20%3D%20new%20BlockBlobClient(cs.value%2C%20%22MyDocuments%22%2C%20%22shopping.rtf%22)%3B%0A%20%20%20%20return%20blobClient.downloadToBuffer(undefined%2Cundefined%2C%20%7B%20abortSignal%20%7D)%3B%0A%7D%0A%0Aconst%20controller%20%3D%20new%20AbortController()%3B%0Aconst%20abortSignal%20%3D%20controller.signal%3B%0Aconst%20list%20%3D%20await%20getShoppingList(%7B%20abortSignal%20%7D)%3B%0A%0A%2F%2F%20then%20sometime%20later%2C%20cancel%20everything%0Acontroller.abort()%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20this%20example%2C%20we%20cancel%20fetching%20the%20connection%20string%20from%20Key%20Vault%20or%2C%20if%20we've%20already%20fetched%20that%2C%20cancel%20the%20download.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--677265866%22%20id%3D%22toc-hId--677116202%22%3EHandling%20AbortErrors%3C%2FH2%3E%0A%3CP%3ECancelled%20operations%20throw%20an%20%3CTT%3EAbortError%3C%2FTT%3E%20which%20prevents%20any%20subsequent%20code%20from%20running.%20This%20ensures%20that%20we%20don't%2C%20for%20example%2C%20try%20to%20create%20a%20%3CTT%3EBlockBlobClient%3C%2FTT%3E%20with%20an%20empty%20key.%20In%20the%20examples%20so%20far%2C%20the%20%3CTT%3EAbortError%3C%2FTT%3E%20is%20not%20handled%20-%20calling%20%3CTT%3Eabort()%3C%2FTT%3E%20on%20a%20controller%20will%20trigger%20an%20unhandled%20exception%20which%20will%20get%20logged%20to%20the%20browser%20console%20or%2C%20sadly%2C%20cause%20Node.js%20to%20exit.%20This%20is%20generally%20not%20good%20practice%2C%20and%20we%20can%20fix%20it%20by%20gracefully%20handling%20the%20%3CTT%3EAbortError%3C%2FTT%3E.%20Here's%20how%20we%20can%20add%20that%20functionality%20using%20our%20last%20example%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3Easync%20function%20getShoppingList(%7B%20abortSignal%20%7D)%20%7B%0A%20%20%20%20const%20cs%20%3D%20await%20secretClient.getSecret('storage-connection-string'%2C%20%7B%20abortSignal%20%7D)%3B%0A%20%20%20%20const%20blobClient%20%3D%20new%20BlockBlobClient(cs.value%2C%20%22MyDocuments%22%2C%20%22shopping.rtf%22)%3B%0A%20%20%20%20return%20blobClient.downloadToBuffer(undefined%2Cundefined%2C%20%7B%20abortSignal%20%7D)%3B%0A%7D%0A%0Aconst%20controller%20%3D%20new%20AbortController()%3B%0Aconst%20abortSignal%20%3D%20controller.signal%3B%0A%0Atry%20%7B%0A%20%20%20%20const%20list%20%3D%20await%20getShoppingList(%7B%20abortSignal%20%7D)%3B%0A%7D%20catch%20(e)%20%7B%0A%20%20%20%20if%20(e.name%20%3D%3D%3D%20'AbortError')%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20abort%20was%20called%20on%20our%20abortSignal%0A%20%20%20%20%20%20%20%20console.log('Operation%20was%20aborted%20by%20the%20user')%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20some%20other%20error%20occurred%20%F0%9F%A4%B7%E2%80%8D%3Amale_sign%3A%0A%20%20%20%20%20%20%20%20console.log('Downloading%20the%20shopping%20list%20failed')%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%2F%2F%20then%20sometime%20later%2C%20cancel%20everything%0Acontroller.abort()%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-1810246967%22%20id%3D%22toc-hId-1810396631%22%3EAdvanced%20uses%3C%2FH2%3E%0A%3CP%3E%3CTT%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F73893%22%20target%3D%22_blank%22%3E%40azure%3C%2FA%3E%2Fabort-controller%3C%2FTT%3E's%20implementation%20of%20%3CTT%3EAbortController%3C%2FTT%3E%20has%20a%20couple%20more%20tricks%20up%20its%20sleeve%20to%20make%20some%20common%20patterns%20easier.%20Please%20note%20that%20these%20APIs%20are%20not%20available%20in%20the%20browser's%20%3CTT%3EAbortController%3C%2FTT%3E.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId--1794158855%22%20id%3D%22toc-hId--1794009191%22%3ECancelling%20with%20a%20timeout%3C%2FH3%3E%0A%3CP%3EFrequently%20you%20want%20to%20give%20an%20operation%20some%20amount%20of%20time%20to%20return%20a%20useful%20result%2C%20and%20if%20it%20hasn't%2C%20you'd%20like%20to%20cancel%20it.%20You%20could%20call%20%3CTT%3EabortSignal.abort()%3C%2FTT%3E%20in%20a%20%3CTT%3EsetTimeout%3C%2FTT%3E%20callback%2C%20but%20this%20pattern%20is%20so%20common%20we%20provide%20a%20bit%20of%20sugar%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3Econst%20list%20%3D%20await%20getShoppingList(%7B%20abortSignal%3A%20AbortController.timeout(1000)%20%7D)%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSPAN%3EThis%20is%20roughly%20equivalent%20to%20the%20following%20code%3A%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3Econst%20controller%20%3D%20new%20AbortController()%3B%0Aconst%20abortSignal%20%3D%20controller.signal%3B%0Aconst%20list%20%3D%20await%20getShoppingList(%7B%20abortSignal%20%7D)%3B%0AsetTimeout(()%20%3D%26gt%3B%20controller.abort()%2C%201000)%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-693353978%22%20id%3D%22toc-hId-693503642%22%3ELinked%20signals%3C%2FH3%3E%0A%3CP%3EIn%20many%20real-world%20applications%2C%20in-progress%20operations%20often%20need%20to%20get%20cancelled%20for%20multiple%20reasons.%20For%20example%2C%20you%20might%20want%20to%20cancel%20a%20download%20after%20a%20certain%20amount%20of%20time%20has%20elapsed%20and%20when%20the%20user%20presses%20the%20cancel%20button.%20The%20Azure%20SDK's%20%3CTT%3EAbortController%3C%2FTT%3E%20supports%20linked%20signals%20for%20this%20purpose%20-%20when%20a%20signal%20is%20aborted%2C%20any%20of%20its%20linked%20signals%20are%20also%20aborted.%3C%2FP%3E%0A%3CP%3ETo%20show%20how%20you%20might%20use%20this%20in%20practice%2C%20we'll%20modify%20our%20previous%20example%20some%20more%20by%20making%20%3CTT%3EgetShoppingList%3C%2FTT%3E%20responsible%20for%20aborting%20operations%20that%20are%20taking%20too%20long%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-javascript%22%3E%3CCODE%3Easync%20function%20getShoppingList(%7B%20abortSignal%2C%20timeout%20%3D%2010000%20%7D)%20%7B%0A%20%20%20%20%2F%2F%20create%20a%20signal%20that%20aborts%20after%20the%20specified%20timeout%0A%20%20%20%20const%20timeoutSignal%20%3D%20AbortController.timeout(timeout)%3B%0A%0A%20%20%20%20%2F%2F%20create%20a%20linked%20signal%20by%20passing%20the%20user-provided%20signal%20and%20the%20timeout%20signal%20together%0A%20%20%20%20const%20controller%20%3D%20new%20AbortController(abortSignal%2C%20timeoutSignal)%3B%0A%20%20%20%20%2F%2F%20now%20controller.signal%20will%20abort%20when%20either%20abortSignal%20or%20timeoutSignal%20abort!%0A%0A%20%20%20%20const%20cs%20%3D%20await%20secretClient.getSecret('storage-connection-string'%2C%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20pass%20our%20fancy%20linked%20signal%0A%20%20%20%20%20%20%20%20abortSignal%3A%20controller.signal%0A%20%20%20%20%7D)%3B%0A%20%20%20%20const%20blobClient%20%3D%20new%20BlockBlobClient(cs.value%2C%20%22MyDocuments%22%2C%20%22shopping.rtf%22)%3B%0A%20%20%20%20return%20blobClient.downloadToBuffer(undefined%2Cundefined%2C%20%7B%0A%20%20%20%20%20%20%20%20abortSignal%3A%20controller.signal%0A%20%20%20%20%7D)%3B%0A%7D%0A%0Aconst%20controller%20%3D%20new%20AbortController()%3B%0Aconst%20abortSignal%20%3D%20controller.signal%3B%0Aconst%20list%20%3D%20await%20getShoppingList(%7B%20abortSignal%20%7D)%3B%0A%0A%2F%2F%20if%20user%20indicates%20they're%20done%20waiting%0Acontroller.abort()%3B%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ELinked%20signals%20are%20also%20useful%20when%20an%20operation%20is%20divided%20into%20many%20sub-tasks%20and%20you%20want%20granular%20control%20over%20which%20parts%20of%20the%20task%20you%20cancel%20while%20also%20being%20able%20to%20cancel%20the%20entire%20operation%20all%20at%20once.%20The%20top-level%20task%20might%20even%20be%20the%20application%20itself.%20For%20example%2C%20if%20you%20want%20to%20handle%20an%20interrupt%20signal%20gracefully%20by%20cancelling%20all%20in-progress%20operations%20inside%20your%20application%2C%20you%20can%20create%20an%20abort%20controller%20at%20application%20startup%2C%20handle%20the%20interrupt%20signal%20by%20calling%20%3CTT%3Eabort()%3C%2FTT%3E%2C%20and%20pass%20that%20signal%20or%20linked%20signals%20to%20all%20calls%20into%20Azure%20SDK%20libraries.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-682850874%22%20id%3D%22toc-hId-683000538%22%3EFurther%20reading%3C%2FH2%3E%0A%3CUL%3E%0A%3CLI%3E%3CA%20href%3D%22https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40azure%2Fabort-controller%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3E%40azure%2Fabort-controller%20readme%20on%20npm%3C%2FA%3E%3C%2FLI%3E%0A%3CLI%3E%3CA%20href%3D%22https%3A%2F%2Fazure.github.io%2Fazure-sdk%2Fgeneral_design.html%23network-requests%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3EAzure%20SDK%20guidelines%20for%20network%20requests%3C%2FA%3E.%3C%2FLI%3E%0A%3C%2FUL%3E%0A%3CH2%20id%3D%22toc-hId--1124603589%22%20id%3D%22toc-hId--1124453925%22%3EWant%20to%20hear%20more%3F%3C%2FH2%3E%0A%3CP%3EFollow%20us%20on%20Twitter%20at%20%3CA%20href%3D%22https%3A%2F%2Ftwitter.com%2FAzureSDK%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3E%40AzureSDK%3C%2FA%3E.%20We'll%20be%20covering%20more%20best%20practices%20in%20cloud-native%20development%20as%20well%20as%20providing%20updates%20on%20our%20progress%20in%20developing%20the%20next%20generation%20of%20Azure%20SDKs.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EContributors%20to%20this%20article%3A%20%3CEM%3E%3CA%20href%3D%22https%3A%2F%2Ftwitter.com%2Fbterlson%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%20target%3D%22_blank%22%3EBrian%20Terlson%3C%2FA%3E%3C%2FEM%3E.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-TEASER%20id%3D%22lingo-teaser-1321797%22%20slang%3D%22en-US%22%3E%3CP%3E%3CSPAN%3ECancelling%20in-progress%20network%20operations%20is%20critical%20for%20applications%20to%20maintain%20responsiveness%20and%20avoid%20doing%20work%20that%20isn't%20needed%20anymore.%26nbsp%3B%20The%20AbortController%20and%20AbortSignal%20are%20common%20objects%20for%20cancelling%20operations%20within%20browsers.%26nbsp%3B%20Learn%20how%20the%20Azure%20SDK%20extends%20these%20classes%20with%20useful%20features%20and%20brings%20them%20to%20Node.js%20environments.%3C%2FSPAN%3E%3C%2FP%3E%3C%2FLINGO-TEASER%3E
Microsoft

 

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.

 

AbortSignal & AbortController

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.

 

Cancelling multiple operations

Often you have multiple in-flight operations that you might want to cancel all at once. To continue our Storage example, maybe you're downloading multiple files in parallel. Or, perhaps you have to fetch a secret from Azure Key Vault before using that secret in a subsequent operation. In that case, you can pass the same signal to each method, and calling abort on the controller will cancel whichever of them is in progress at that time.

 

async function getShoppingList({ abortSignal }) {
    const cs = await secretClient.getSecret('storage-connection-string', { abortSignal });
    const blobClient = new BlockBlobClient(cs.value, "MyDocuments", "shopping.rtf");
    return blobClient.downloadToBuffer(undefined,undefined, { abortSignal });
}

const controller = new AbortController();
const abortSignal = controller.signal;
const list = await getShoppingList({ abortSignal });

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

 

In this example, we cancel fetching the connection string from Key Vault or, if we've already fetched that, cancel the download.

Handling AbortErrors

Cancelled operations throw an AbortError which prevents any subsequent code from running. This ensures that we don't, for example, try to create a BlockBlobClient with an empty key. In the examples so far, the AbortError is not handled - calling abort() on a controller will trigger an unhandled exception which will get logged to the browser console or, sadly, cause Node.js to exit. This is generally not good practice, and we can fix it by gracefully handling the AbortError. Here's how we can add that functionality using our last example:

 

async function getShoppingList({ abortSignal }) {
    const cs = await secretClient.getSecret('storage-connection-string', { abortSignal });
    const blobClient = new BlockBlobClient(cs.value, "MyDocuments", "shopping.rtf");
    return blobClient.downloadToBuffer(undefined,undefined, { abortSignal });
}

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

try {
    const list = await getShoppingList({ abortSignal });
} catch (e) {
    if (e.name === 'AbortError') {
        // abort was called on our abortSignal
        console.log('Operation was aborted by the user');
    } else {
        // some other error occurred 🤷‍:male_sign:
        console.log('Downloading the shopping list failed');
    }
}

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

 

 

Advanced uses

@azure/abort-controller's implementation of AbortController has a couple more tricks up its sleeve to make some common patterns easier. Please note that these APIs are not available in the browser's AbortController.

 

Cancelling with a timeout

Frequently you want to give an operation some amount of time to return a useful result, and if it hasn't, you'd like to cancel it. You could call abortSignal.abort() in a setTimeout callback, but this pattern is so common we provide a bit of sugar:

 

const list = await getShoppingList({ abortSignal: AbortController.timeout(1000) });

 

This is roughly equivalent to the following code:

 

const controller = new AbortController();
const abortSignal = controller.signal;
const list = await getShoppingList({ abortSignal });
setTimeout(() => controller.abort(), 1000);

 

 

Linked signals

In many real-world applications, in-progress operations often need to get cancelled for multiple reasons. For example, you might want to cancel a download after a certain amount of time has elapsed and when the user presses the cancel button. The Azure SDK's AbortController supports linked signals for this purpose - when a signal is aborted, any of its linked signals are also aborted.

To show how you might use this in practice, we'll modify our previous example some more by making getShoppingList responsible for aborting operations that are taking too long:

 

async function getShoppingList({ abortSignal, timeout = 10000 }) {
    // create a signal that aborts after the specified timeout
    const timeoutSignal = AbortController.timeout(timeout);

    // create a linked signal by passing the user-provided signal and the timeout signal together
    const controller = new AbortController(abortSignal, timeoutSignal);
    // now controller.signal will abort when either abortSignal or timeoutSignal abort!

    const cs = await secretClient.getSecret('storage-connection-string', {
        // pass our fancy linked signal
        abortSignal: controller.signal
    });
    const blobClient = new BlockBlobClient(cs.value, "MyDocuments", "shopping.rtf");
    return blobClient.downloadToBuffer(undefined,undefined, {
        abortSignal: controller.signal
    });
}

const controller = new AbortController();
const abortSignal = controller.signal;
const list = await getShoppingList({ abortSignal });

// if user indicates they're done waiting
controller.abort();

 

Linked signals are also useful when an operation is divided into many sub-tasks and you want granular control over which parts of the task you cancel while also being able to cancel the entire operation all at once. The top-level task might even be the application itself. For example, if you want to handle an interrupt signal gracefully by cancelling all in-progress operations inside your application, you can create an abort controller at application startup, handle the interrupt signal by calling abort(), and pass that signal or linked signals to all calls into Azure SDK libraries.

 

Further reading

Want to hear more?

Follow us on Twitter at @AzureSDK. We'll be covering more best practices in cloud-native development as well as providing updates on our progress in developing the next generation of Azure SDKs.

 

Contributors to this article: Brian Terlson.