How to cancel timeout inside of Javascript Promise?

前端 未结 4 1679
迷失自我
迷失自我 2020-12-29 06:04

I\'m toying with promises in JavaScript and tried to promisify setTimeout function:

function timeout(ms) {
  return new Promise(function(resolve, reject) {
          


        
4条回答
  •  长情又很酷
    2020-12-29 06:48

    What you can do it that, you can return a canceller from your timeout function and invoke it when needed. This way you do not need to store the timeoutid globally (or on the outer scope) and also this can manage multiple calls to the function as well. Each instance of the object return by the function timeout will have its own canceler that can perform the cancellation.

    function timeout(ms) {
      var timeout, promise;
    
      promise = new Promise(function(resolve, reject) {
        timeout = setTimeout(function() {
          resolve('timeout done');
        }, ms);
      }); 
    
      return {
               promise:promise, 
               cancel:function(){clearTimeout(timeout );} //return a canceller as well
             };
    }
    
    var timeOutObj =timeout(3000); 
    
    timeOutObj.promise.then(function(result) { 
      console.log(result); // timeout done
    });
    
    //Cancel it.
    timeOutObj.cancel();
    

    Plnkr

提交回复
热议问题