Created
October 18, 2020 10:43
-
-
Save Mahdhir/1f6609ea75f45c07801168c18cdb3812 to your computer and use it in GitHub Desktop.
This file contains 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 timeout(delay) { | |
let cancel; | |
const wait = new Promise(resolve => { | |
const timer = setTimeout(() => resolve(false), delay); | |
cancel = () => { | |
clearTimeout(timer); | |
resolve(true); | |
}; | |
}); | |
wait.cancel = cancel; | |
return wait; | |
} | |
function doWork() { | |
const workFactor = Math.floor(600*Math.random()); | |
const work = timeout(workFactor); | |
const result = work.then(canceled => { | |
if (canceled) | |
console.log('Work canceled'); | |
else | |
console.log('Work done in', workFactor, 'ms'); | |
return !canceled; | |
}); | |
result.cancel = work.cancel; | |
return result; | |
} | |
function attemptWork() { | |
const work = doWork(); | |
return Promise.race([work, timeout(300)]) | |
.then(done => { | |
if (!done) | |
work.cancel(); | |
return (done ? 'Work complete!' : 'I gave up'); | |
}); | |
} | |
attemptWork().then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment