Last active
October 25, 2019 01:06
-
-
Save horiuchie/fd28ba5d9cd8d02f0b24efafef3c71c1 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
import Promise from 'bluebird'; | |
Promise.config({ cancellation: true }); | |
const cancellableDelay = (time, cancelHandler) => | |
new Promise((resolve, reject, onCancel) => { | |
const timer = setTimeout(resolve, time); | |
onCancel(() => { | |
clearTimeout(timer); | |
cancelHandler(); | |
}); | |
}); | |
//////////////////// example //////////////////// | |
console.log(`start at ${new Date()}`); | |
const delayPromise = cancellableDelay(5000, () => { | |
console.log(`cancelled at ${new Date()}`); | |
}); | |
delayPromise.then(() => { | |
console.log(`resolved at ${new Date()}`); | |
}); | |
/* | |
cancel 2 seconds later. | |
*/ | |
setTimeout(() => { | |
delayPromise.cancel(); | |
}, 2000); | |
/* | |
resolve 5 seconds later. | |
setTimeout(() => { | |
delayPromise.cancel(); // no meaning | |
}, 6000); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment