I am trying to call a series of promises sequentially using a for loop, but I am having trouble getting to work in the right order. Theoretically speaking, the console should log the first block but it instead logging the second (implying that the promises are all called at the same time as compared to the second promise only being called after the first).
I thought this might be similar to this link, but I think I'm declaring the function rather than calling it in the then declaration? How to sequentially run promises with Q in Javascript?
Expected output:
starting: 3
ending: 3
starting: 2
ending: 2
starting: 1
ending: 1
Actual output:
starting: 3
starting: 2
starting: 1
ending: 1
ending: 2
ending: 3
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope, $q, $timeout) {
var temp = $q.when({});
var arr = [3, 2, 1];
arr.forEach(function(element) {
temp = temp.then(delay(element));
})
function delay(timing) {
var deferred = $q.defer();
console.log('starting: ' + timing)
$timeout(function() {
console.log('ending: ' + timing);
deferred.resolve(timing);
}, timing * 1000);
return deferred.promise;
}
});