Created
February 13, 2019 17:52
-
-
Save masnun/aabb1dac22d2526c07eb232afb783498 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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