javascript - Problems trying to use for loops with sequential promises (q) -
i trying call series of promises sequentially using loop, having trouble getting work in right order. theoretically speaking, console should log first block instead logging second (implying promises called @ same time compared second promise being called after first).
i thought might similar link, think i'm declaring function rather calling in declaration? how sequentially run promises 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; } });
your fiddle different code in question. there. there missing 1 return statement.
you right: temp = temp.then(delay(element));
calls delay
. want instead returning function call delay
. (you had in fiddle.)
the thing missing there return
return :)
here working fiddle: http://jsfiddle.net/4k6t9/6/
Comments
Post a Comment