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
4.0k views
in Technique[技术] by (71.8m points)

Periodically resolving a promise in javascript

Let’s say I want to resolve some promise every 2 seconds AFTER the function is run.

I tried a pattern like this at first: setInterval(MyAsyncFunction, 2000), but of course this does not wait for the promise to resolve before calling the function again.

I also tried setInterval(async () => await MyAsyncFunction(), 2000), but this is basically the same thing since I’m just wrapping it in another promise that will resolve while the setInterval is ticking down.

Is there a way to do what I am trying to do with setInterval or is there some alternative way to do this using setTimeout?


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

1 Reply

0 votes
by (71.8m points)

A Promise resolves once only, so therefore cannot, by definition, resolve periodically.

If you define a delay function, which returns a promise that resolves after timeout ms...

const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout));

you could use it in an async loop:

async function foo(){
    for(let i = 0; i < 100; ++i){
        console.log("azrael");
        await delay(2000);
    }
}

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

...