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

前端 未结 7 1919
囚心锁ツ
囚心锁ツ 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:17

    The easiest way is to create a function and manually iterate over all the objects in the array after each promise is resolved.

    var delayedFORLoop = function (array) {
        var defer = $q.defer();
    
        var loop = function (count) {
            var item = array[count];
    
            // Example of a promise to wait for
            myService.DoCalculation(item).then(function (response) {
    
            }).finally(function () {
              // Resolve or continue with loop
                if (count === array.length) {
                    defer.resolve();
                } else {
                    loop(++count);
                }
            });
        }
    
        loop(0); // Start loop
        return defer.promise;
    }
    
    // To use:
    delayedFORLoop(array).then(function(response) {
        // Do something
    });
    

    Example is also available on my GitHub: https://github.com/pietervw/Deferred-Angular-FOR-Loop-Example

    0 讨论(0)
提交回复
热议问题