与this question类似,但我并不是询问promises一般是如何工作的,而是特别想知道:
在返回Promise的东西中包装setTimeout的标准/最佳方式是什么?我在考虑类似于Angular的$timeout function,但不是特定于Angular的。
发布于 2015-12-14 03:37:39
在浏览器中
首先,没有--没有内置的功能。许多增强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(Error("Cancelled"))};
return p;
}然后您可以执行以下操作:
delay(1000).then(/* ... do whatever */);或
doSomething().then(function(){ return delay(1000); }).then(doSomethingElse);如果我们只需要ES2015的基本功能,那就更简单了,如下所示:
let delay = ms => new Promise(r => setTimeout(r, ms));在节点中
您可以在setTimeout上使用util.promisify来获取delay函数-这意味着您不必再使用new Promise构造函数。
发布于 2015-12-14 03:31:19
下面是我将如何实现它:
function delay(duration, func) {
var args = Array.prototype.slice.call(arguments, 2);
return new Promise(function (resolve) {
setTimeout(function () {
resolve(func.apply(null, args));
}, duration);
});
}(ES5-有意选择的语法)
但也许有一个通用库已经做到了这一点,或者是一种更好的方式。
发布于 2017-11-11 21:51:51
如果您需要适当的取消promise timeout,类似于clearTimeout -直接从setTimeout返回promise并不方便。尤其是在try...finally块中与ES7 async / await一起使用时。最好使用单独的变量来处理超时。我已经将这种方法实现为小型await-timeout包。它的工作原理如下:
import Timeout from 'await-timeout';
async function foo() {
const timeout = new Timeout();
try {
const fetchPromise = fetch('https://example.com');
const timerPromise = timeout.set(1000).then(() => console.log('Timeout!'));
await Promise.race([fetchPromise, timerPromise]);
} finally {
timeout.clear();
}
}在本例中,在获取成功或出现任何错误的情况下,超时肯定会被清除,并且不会调用console.log('Timeout!')。
https://stackoverflow.com/questions/34255351
复制相似问题