是否有返回 ES6 承诺的 setTimeout 版本? [英] Is there a version of setTimeout that returns an ES6 promise?

查看:40
本文介绍了是否有返回 ES6 承诺的 setTimeout 版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于这个问题,但不是询问如何承诺一般有效,我特别想知道:

Similar to this question, but rather than asking about how promises work in general, I specifically want to know:

包装setTimeout 在返回 Promise 的东西中?我在想像 Angular 的 $timeout 函数,但不是特定于 Angular.

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.

推荐答案

在浏览器中

首先不是 - 没有内置的.许多增强 ES2015 的库都像 bluebird 鞭子一样承诺.

In Browsers

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

然后你可以这样做:

delay(1000).then(/* ... do whatever */);

或者

 doSomething().then(function(){ return delay(1000); }).then(doSomethingElse);

如果我们只想要 ES2015 中的基本功能,那就更简单了:

If we only want the basic functionality in ES2015, it's even simpler as:

let delay = ms => new Promise(r => setTimeout(r, ms));

在节点

您可以在 setTimeout 上使用 util.promisify 来获取 delay 功能 - 这意味着您不必使用 new Promise 构造函数了.

In Node

You can use util.promisify on setTimeout to get a delay function back - meaning you don't have to use the new Promise constructor anymore.

这篇关于是否有返回 ES6 承诺的 setTimeout 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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