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  

http://jsfiddle.net/4k6t9/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

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -