Angular promise in async loop function

前端 未结 1 608
遥遥无期
遥遥无期 2021-01-03 01:39

I have an upload function which loops through the selected files and adds them on the servers file system.

Upload factory

app.factor         


        
相关标签:
1条回答
  • 2021-01-03 02:23

    You're right $q.all() is the way to go here (totally untested -- but i think this is at least the right direction..):

    app.factory('uploadFactory', function ($upload, $q) {
    
        var uploadFactory = {};
    
        var image = {
            Models: [],
            Images: [],
            uploadImages: function () {
    
                var promises = [];
    
                for (var i = 0; i < this.Models.length; i++) {
    
                    var $file = this.Models[i].file;
                    var response = $upload
                        .upload({
                            url: "/api/upload/",
                            method: "POST",
                            file: $file
                        })
                        .success(function (data, result) {
                            // Add returned file data to model
                            var imageObject = {
                                Path: data.Path,
                                Description: $file.Description,
                                Photographer: $file.Photographer
                            };
                            image.Images.push(imageObject);
                        });
    
                    promises.push(response);
                }
                return $q.all(promises);
            }
        };
    
        uploadFactory.image = function () {
            return image;
        };
    
        return uploadFactory;
    });
    
    0 讨论(0)
提交回复
热议问题