Promise chaining when using $timeout

Here you go. What I did is essentially added a success function in the then part of the code.

$timeout(pushA, 5000).then(function(success) {
    pushB()
  });

Here is the working demo.

You can also add an error function like this

 $timeout(pushA, 5000).then(function(success) {
    pushB()
  },function(error){console.log("Error");});

While searching for this answer, I also came across this very helpful link


Don't invoke the functions inside the .then methods.

  ̶$̶q̶.̶w̶h̶e̶n̶(̶p̶u̶s̶h̶A̶(̶)̶)̶.̶t̶h̶e̶n̶(̶p̶u̶s̶h̶B̶(̶)̶)̶;̶
  $q.when(pushA()).then(pushB);

  ̶$̶t̶i̶m̶e̶o̶u̶t̶(̶p̶u̶s̶h̶A̶,̶ ̶5̶0̶0̶0̶)̶.̶t̶h̶e̶n̶(̶p̶u̶s̶h̶B̶(̶)̶)̶;̶    
  $timeout(pushA, 5000).then(pushB);

Instead pass the functions as arguments to the .then method. The $q service will hold those functions to be invoked later.

The way the $q service works is it stores the argument of the .then method as a function to be invoked later. In this case, the $q service was storing the value returned by pushB() with the side effect of pushing B immediately onto the array.

The DEMO on JSFiddle