简体   繁体   中英

Problems trying to use for loops with sequential promises (q)

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 

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 is slightly different from the code in the question. But you where nearly there. There was only missing one return statement.

You are right: temp = temp.then(delay(element)); calls delay . What you want instead is returning a function which will call delay . (You had that in the fiddle.)

The only thing missing there was a return to return it :)

Here is the working fiddle: http://jsfiddle.net/4k6t9/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM