I'm toying with promises in JavaScript and tried to promisify setTimeout function:
function timeout(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('timeout done');
}, ms);
});
}
var myPromise=timeout(3000);
myPromise.then(function(result) {
console.log(result); // timeout done
})
Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. timeout
returns Promise
object hence I loose access to value that setTimeout
returns and cannot cancel timeout via clearTimeout
. What woud be the best way to do it?
BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview