Skip to content

Instantly share code, notes, and snippets.

@masnun
Created February 13, 2019 17:52
Show Gist options
  • Save masnun/aabb1dac22d2526c07eb232afb783498 to your computer and use it in GitHub Desktop.
Save masnun/aabb1dac22d2526c07eb232afb783498 to your computer and use it in GitHub Desktop.
function wait(signal, ms) {
return new Promise((res, rej) => {
const timeOut = setTimeout(() => {
console.log("I was called");
res("ok");
}, ms);
signal.catch(err => {
rej(err);
clearTimeout(timeOut);
});
});
}
function createCancellableSignal() {
const ret = {};
ret.signal = new Promise((resolve, reject) => {
ret.cancel = () => {
reject(new Error("Promise was cancelled"));
};
});
return ret;
}
const { signal, cancel } = createCancellableSignal();
const promise = wait(signal, 1000);
promise.then(res => console.log(res)).catch(err => console.log(err));
cancel();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment