Make angular.forEach wait for promise after going to next object

前端 未结 7 1941
囚心锁ツ
囚心锁ツ 2020-12-03 03:25

I have a list of objects. The objects are passed to a deferred function. I want to call the function with the next object only after the previous call is resolved. Is there

7条回答
  •  甜味超标
    2020-12-03 04:10

    Yes you can use angular.forEach to achieve this.

    Here is an example (assuming objects is an array):

    // Define the initial promise
    var sequence = $q.defer();
    sequence.resolve();
    sequence = sequence.promise;
    
    angular.forEach(objects, function(val,key){
        sequence = sequence.then(function() {
            return doSomething(val);
        });
    });
    

    Here is how this can be done using array.reduce, similar to @friend00's answer (assuming objects is an array):

    objects.reduce(function(p, val) {
        // The initial promise object
        if(p.then === undefined) {
            p.resolve(); 
            p = p.promise;
        }
        return p.then(function() {
            return doSomething(val);
        });
    }, $q.defer());
    

提交回复
热议问题