替代幻灯片的多个承诺

时间:2014-05-29 14:05:08

标签: javascript angularjs angular-ui-router

我有一个用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);
  });
 });
});

1 个答案:

答案 0 :(得分:0)

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

只需为所有承诺重用一个变量。然后,当您需要取消它时,调用$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); 
}

Demo