简体   繁体   English

承诺解决得太快

[英]Promise resolved too fast

I am using Promises and in the meanwhile i have a loading animation. 我正在使用Promises,同时我有一个加载动画。
the problme is that my promise is resolved fast and the loader is quickly disappear. 问题是我的诺言很快得到解决,装载机很快消失了。

So i want to launch a promise and if the promise is resolved before 3 sec wait the remaining time. 因此,我想发布一个承诺,如果该承诺在3秒之前解决,请等待剩余时间。

Example

export const operation = () => {

  const a = new Date();

  const myPromise = doAction().then(() => {

   const b = new Date();

   if((b - a) < 3000)
      operationIsDone();
   else
     setTimeout(() => {operationIsDone();}, b - a)

  });  
}

Is there any npm or a better way doing it? 有没有npm或更好的方法呢? Thanks in advance. 提前致谢。

It is much easier to use a second promise that just runs the minimum waiting time. 使用只需等待最少等待时间的第二个承诺要容易得多。 Then use Promise.all to wait for both to finish. 然后使用Promise.all等待两者完成。 That way, your script will always wait at least the default delay but also longer if yourOwnPromise takes longer than that. 这样,您的脚本将始终至少等待默认延迟,但是如果yourOwnPromise花费的时间更长,则yourOwnPromise时间也会更长。

 const wait = delay => new Promise(resolve => setTimeout(resolve, delay)); const doAction = () => wait(500); // TODO replace this with your own function const yourOwnPromise = doAction(); yourOwnPromise.then(() => { console.log('yourOwnPromise resolved now'); }); Promise.all([yourOwnPromise, wait(3000)]).then(() => { console.log('both resolved now'); }); 

See Promise.all for details. 有关详细信息,请参见Promise.all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM