如何取消Javascript Promise内部的超时? [英] How to cancel timeout inside of Javascript Promise?

查看:222
本文介绍了如何取消Javascript Promise内部的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript中的promises并试图宣传setTimeout函数:

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
})

相当直截了当但我想知道如何在诺言结算之前取消我的超时。 timeout 返回 Promise 对象因此我失去了对 setTimeout 返回并且无法通过 clearTimeout 取消超时。什么是最好的方法呢?

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没有真正的目的,我只是想知道如何处理这个问题。我也在这里 http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview

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

推荐答案

你可以做什么,你可以从你的超时函数返回一个取消器并在需要时调用它。这样您就不需要全局(或在外部作用域)存储 timeoutid ,这也可以管理对函数的多次调用。函数 timeout 返回的对象的每个实例都有自己的取消器,可以执行取消。

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

Plnkr

这篇关于如何取消Javascript Promise内部的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆