繁体   English   中英

如何使用promise来链接几个setTimeout函数?

[英]How do I use a promise to chain several setTimeout functions?

我的应用程序中有几个setTimeout函数在不同的时间被调用(有些在页面加载后被同时调用)

我试图找出压缩和增强此代码的方法。 下面是我调用的3个setTimeout函数的示例,实际上我的应用程序中有更多:

  setTimeout(function () {
    $('.itemOne').css({
      'visibility': 'visible'
    }).addClass('animated slideInRight animate-duration-100');
  }, 1000);

  setTimeout(function () {
    $('.itemTwo').css({
      'background-color': 'rgba(0, 27, 53, 0.8)',
    });
  }, 1200);

  setTimeout(function () {
    $('.itemThree').css({
      'background-color': 'rgba(136, 211, 192, 0.25)',
    });
  }, 1200);

链接这些是使用承诺链使这个代码紧凑和整洁的最佳方法吗? 或者还有另一种方式吗?

不确定这是不是你想要的。 我创建了一个工厂包装你的逻辑以及一旦所有promises解决后触发的回调。 如果您需要进一步的帮助,请告诉我! 干杯!

function createCssPromise($target, styleObj, timeout) {
  const { newStyle, newClass } = styleObj;

  return new Promise((resolve) => {
    setTimeout(() => {
      if (newStyle) {
        $target.css(newStyle); 
      }
      if (newClass) {
        $target.addClass(newClass);
      }

      resolve();
     }, timeout);
  });
}

const targetObj = $('.itemOne');
const styleObj = { 
  newStyle: { 'visibility': 'visible'}, 
  newClass: 'animated slideInRight animate-duration-100', 
}; 
const timeout = 1000;

const firstPromise = new createCssPromise(targetObj, styleObj, timeout);
const secondPromise... //follow the pattern
const thirdPromise...  // follow the pattern

Promise.all([firstPromise, secondPromise, thirdPromise]
  .then(() => console.log('done!'));

* <= IE11本身不支持Promise.all。

请注意,这并不能回答关于使用promises的确切问题,但是在你提出的关于使代码更紧凑和更整洁的问题中。 您可以很容易地将其重构为以下内容,使您的所有调用超时一个内衬:

function applyCssWithTimeout($target, cssToApply, timeout, classesToAdd) {
  setTimeout(function() { 
    $target.css(cssToApply).addClass(classesToAdd);
  }, timeout);
}

applyCssWithTimeout($('.itemOne'), { 'visibility': 'visible' }, 1000, 'animated slideInRight animate-duration-100');
applyCssWithTimeout($('.itemTwo'), { 'background-color': 'rgba(0, 27, 53, 0.8)' }, 1200);
applyCssWithTimeout($('.itemThree'), { 'background-color': 'rgba(136, 211, 192, 0.25)' }, 1200);

暂无
暂无

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

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