CancelablePromise
A promise you can stop.
Installation
In Browser
Include assets
Simply download and include with a script tag, CancelablePromise
will be registered as a global variable.
<script src="../lib/cancelable-promise.global.js"></script>
<script>
var promise = new CancelablePromise((resolve, reject, onCancel) => {
setTimeout(resolve, 1000);
onCancel(() => console.log('canceled'));
});
promise.cancel();
</script>
CDN
unpkg
<script src="https://unpkg.com/@nextgis/cancelable-promise"></script>
jsdelivr
<script src="https://cdn.jsdelivr.net/npm/@nextgis/cancelable-promise"></script>
We recommend linking to a specific version number /cancelable-promise@[version]
In Node.js
npm install @nextgis/cancelable-promise
Usage
Catch CancelError
import CancelablePromise from "@nextgis/cancelable-promise";
const promise = new CancelablePromise((resolve, reject) => {
setTimeout(() => resolve(), 100);
}).catch((er) => {
if (er.name === "CancelError") {
}
throw er;
});
promise.cancel();
Handle onCancel
callback
import CancelablePromise from "@nextgis/cancelable-promise";
const promise = new CancelablePromise((resolve, reject, onCancel) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = () => {
resolve(xhr.responseText);
};
xhr.onerror = (er) => {
reject(er);
};
onCancel(() => {
xhr.abort();
});
xhr.send();
});
promise.cancel();
Check out the API Documentation
Commercial support
Need to fix a bug or add a feature to @nextgis/cancelable-promise
? We provide custom development and support for this software. Contact us to discuss options!