Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - Is there a version of setTimeout that returns an ES6 promise?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...