是否有一个返回ES6承诺的setTimeout版本? [英] Is there a version of setTimeout that returns an ES6 promise?
问题描述
类似于此问题,而不是询问如何承诺一般工作,我特意想知道:
什么是标准/最好的方式来包装 setTimeout ,返回一个 Promise ?我正在想像Angular的 $ timeout
function ,但不是Angular。
首先没有 - 没有内置这个。许多增强ES2015的图书馆承诺像蓝鸟鞭子一样。
我认为另一个答案使执行功能和延迟混淆,同时也造成无法取消的超时。我会简单地写:
function delay(ms){
var ctr,rej,p = new Promise(function(resolve,reject){
ctr = setTimeout(resolve,ms);
rej = reject;
});
p.cancel = function(){clearTimeout(ctr); REJ(错误( 取消))};
return p;
}
然后你可以做:
$ pre>
delay(1000).then(/ * ... do whatever * /);
或
doSomething()。then(function(){return delay(1000);})然后(doSomethingElse);
如果我们只想要ES2015的基本功能,那就更简单了:
let delay = ms =>新的Promise(r => setTimeout(r,ms));
Similar to this question, but rather than asking about how promises work in general, I specifically want to know:
What is the standard/best way to wrap setTimeout in something that returns a Promise? I'm thinking something like Angular's $timeout
function, but not Angular specific.
First of all no - there is no built in for this. Lots of libraries that enhance ES2015 promises like bluebird whip with it.
I think the other answer conflates executing the function and a delay, it also creates timeouts that are impossible to cancel. I'd write it simply as:
function delay(ms){
var ctr, rej, p = new Promise(function (resolve, reject) {
ctr = setTimeout(resolve, ms);
rej = reject;
});
p.cancel = function(){ clearTimeout(ctr); rej(Error("Cancelled"))};
return p;
}
Then you can do:
delay(1000).then(/* ... do whatever */);
Or
doSomething().then(function(){ return delay(1000); }).then(doSomethingElse);
If we only want the basic functionality in ES2015, it's even simpler as:
let delay = ms => new Promise(r => setTimeout(r, ms));
这篇关于是否有一个返回ES6承诺的setTimeout版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!