Instructor: In order to demonstrate an effective use of the abort controller, I have created a simple checkout interface that we will use to initiate a payment request. We will cancel the transaction while it is processing, effectively intercepting the promise before it resolves or errors out.
In an effort to maintain modularity, I have extracted the abort controller logic into a separate file. Here you will see that we export only the relevant pieces that will enable us to cancel down requests anywhere in our application.
As we take a look at checkout.js, which contains the nuts and bolts of the application, what's important here is this transaction status component. I want you to focus on this.handle cancel, which, when invoked, will call the abort method on the abort controller.
Let's dive into transaction status. Here we have a view for each possible state that will render based on the value of the status prop that flows down from the checkout component. When a transaction is initiated and we enter the processing state, we have two options, do nothing and allow the payment to process, ideally returning a success, or we can cancel the request before it resolves.
As we go back to the checkout view, you will see that clicking the pay now call to action invokes this.handle checkout. This.handle checkout invokes this.checkout, the method that returns the promise. Within the body of the promise, I have attached an event listener for the abort error event to the signal property of the abort controller.
When an abort error is fired, the promise is rejected with a DOM exception. We need to pass a descriptive message along with the name of the error that caused the exception.
If we go back to the catch block of the checkout promise, you will see that we have a conditional that checks the error that caused the exception is an abort error. If so, the state of the status prop is updated to canceled. This will cause the UI to update and re-render the appropriate view.