繁体   English   中英

幻灯片放映的多种承诺的替代方案

[英]Alternative to multiple promises for slideshow

我有一个循环,可使用ui-router创建幻灯片。 它工作正常,但我认为这不是要走的路。 有人可以提供替代方法来宣布如此多的承诺吗?

define(['./module'], function (controllers) {
  controllers.controller('homeController', function($timeout, $state, $scope) {

  var promise;
  promise = $timeout(function slide() {
    $state.transitionTo('home.construcao');
       promise1 = $timeout(function () {
          $state.transitionTo('home.saude');
       }, 3000);

       promise2 = $timeout(function () {
          $state.transitionTo('home.business');
       }, 5000);

       promise3 = $timeout(function () {
          $state.transitionTo('home.premium');
       }, 7000);
       promise4 = $timeout(slide, 9000);
  }, 0);
  $scope.$on('$locationChangeStart', function(){
    $timeout.cancel(promise);
    $timeout.cancel(promise1);
    $timeout.cancel(promise2);
    $timeout.cancel(promise3);
    $timeout.cancel(promise4);
    console.log(promise);
  });
 });
});

是的,实际上,您不需要像示例代码中那样将多个promise嵌套在另一个promise中。

只需为所有promise重用一个变量。 然后,当您需要取消它时,调用$timeout.cancel传递那个promise变量作为参数:

// slide objects contain state labels plus amount of time each slide will
// appear for
var slides = [ 
   {state: 'home.construcao', time: 3000},
   {state: 'home.saude', time: 2000},
   {state: 'home.business', time: 2000},
   {state: 'home.premium', time: 2000}
];

var index = 0; // initialize index (start with first slide)
var promise; // set var here so it's available in scope for $timeout.cancel later

// assign anonymous function to named var so it can be referenced by $timeout
var slide = function(){ 
   // show slide, accessing state label string from array
   $state.transitionTo(slides[index].state); 
   // call $timeout to recursively call this function, which will show next slide
   promise = $timeout(slide, slides[index].time);
   // if at the last value in the slide array, reset back to the first for
   // next slide to be shown
   index = (index < slides.length - 1) ? index + 1 : 0;
};

slide(); // start slideshow

$scope.$on('$locationChangeStart', function(){
   // interrupt $timeout when event fires; pause slideshow
   $timeout.cancel(promise); 
}

演示

暂无
暂无

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

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