Promise chaining when using $timeout

Viewed 14243

I'm trying to understand the promise API and chaining, particularly the timing when $timeoutis used with .then(). What I had expected from the following is that since $timeout returns a promise, .then() would not be called until it had resolved.

But instead of ABAB, it's ABBA all the time.

How can I use the promise API to ensure that a long-running call (or delayed call using $timeout) is actually complete before the .then() gets executed?

Code

angular
  .module('app', [])
  .controller('ThenCtrl', ThenCtrl);

function ThenCtrl($timeout, $q) {
  var vm = this;

  vm.items = [];

  $q.when(pushA()).then(pushB());

  $timeout(pushA, 5000).then(pushB());

  function pushA() {
    vm.items.push('A');
  }

  function pushB() {
    vm.items.push('B');
  }
}

Markup

<div ng-app="app">
  <div ng-controller="ThenCtrl as vm">
    {{vm.items}}
  </div>
</div>

I've set up a fiddle: https://jsfiddle.net/kan3c61t/

3 Answers
Related