Page updated Nov 14, 2023

Cancel API requests

You may cancel any request made through API category by keeping a reference to the promise returned.

const promise = API.get(myApiName, myPath, myInit); try { await promise; } catch (error) { console.log(error); // If the error is because the request was cancelled you can confirm here. if(API.isCancel(error)) { // "my message for cancellation" console.log(error.message); // handle user cancellation logic } } ... // To cancel the above request API.cancel(promise, "my message for cancellation");
1const promise = API.get(myApiName, myPath, myInit);
2
3try {
4 await promise;
5} catch (error) {
6 console.log(error);
7 // If the error is because the request was cancelled you can confirm here.
8 if(API.isCancel(error)) {
9 // "my message for cancellation"
10 console.log(error.message);
11 // handle user cancellation logic
12 }
13}
14
15...
16
17// To cancel the above request
18API.cancel(promise, "my message for cancellation");

You need to ensure that the promise returned from API.get() or any other API calls has not been modified. Typically async functions wrap the promise being returned into another promise. For example, the following will not work

async function makeAPICall() { return API.get(myApiName, myPath, myInit); } const promise = makeAPICall(); // The following will NOT cancel the request. API.cancel(promise, 'my error message');
1async function makeAPICall() {
2 return API.get(myApiName, myPath, myInit);
3}
4const promise = makeAPICall();
5
6// The following will NOT cancel the request.
7API.cancel(promise, 'my error message');