JSFiddle - React, Tailwind, and code Playground
HTML
<label>
<input type="checkbox" id="chk"> Cancel
</label>
<br><input type="button" id="btn" value="Go">
JavaScript
function cancelableThen(f) {
const wrapper = value => f(value);
wrapper.cancel = () => {
f = value => value;
};
return wrapper;
}
function doSomething(value) {
// Do something with the value
log("Got value: " + value);
return value.toUpperCase();
}
function getAPromise() {
return new Promise(resolve => {
setTimeout(() => {
log("Resolving");
resolve("foo");
}, 500);
});
}
function log(msg) {
const p = document.createElement("pre");
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
document.getElementById("btn").addEventListener("click", function() {
const cancelFlag = document.getElementById("chk").checked;
log("Cancelling: " + cancelFlag);
const cb = cancelableThen(doSomething);
getAPromise()
.then(cb)
.then(value => {
log("Final then got: " + value);
})
.catch(e => log("Error: " + e));
if (cancelFlag) {
cb.cancel();
}
})