角度异步功能不等待继续之前完成

时间:2014-02-11 21:17:52

标签: javascript angularjs

我有一个上传功能,它循环选定的文件并将它们添加到服务器文件系统上。

上传功能:

$scope.uploadImages = function () {
        for (var i = 0; i < $scope.imageModels.length; i++) {
            var $file = $scope.imageModels[i].file;
            (function (index) {
                $upload
                    .upload({
                        url: "/api/upload/",
                        method: "POST",
                        data: { type: 'img', object: 'ship' },
                        file: $file
                    })
                    .progress(function (evt) {
                        $scope.imageProgress[index] = parseInt(100.0 * evt.loaded / evt.total);
                    })
                    .success(function (data) {
                        $scope.imageProgressbar[index] = 'success';

                        // Add returned file data to model
                        $scope.imageModels[index].Path = data.Path;
                        $scope.imageModels[index].FileType = data.FileType;
                        $scope.imageModels[index].FileSize = $scope.imageModels[index].file.size;

                        var image = {
                            Path: data.Path,
                            Description: $scope.imageModels[index].Description,
                            Photographer: $scope.imageModels[index].Photographer
                        };
                        $scope.images.push(image);
                    })
                    .error(function (data) {
                        $scope.imageProgressbar[index] = 'danger';
                        $scope.imageProgress[index] = 'Upload failed';

                        alert("error: " + data.ExceptionMessage);
                    });
            })(i);
        }
        return $scope.images;
    }
};

如果我单独调用它可以正常工作,但当我将其与其他功能放在一起时,它似乎无法完成:

 $scope.create = function () {
    $scope.ship = {};

    // This function is asynchronous
    $scope.ship.Images = $scope.uploadImages();

    // Here $scope.ship don't contain any Images
    angular.extend($scope.ship, $scope.shipDetails);

    shipFactory.createShip($scope.ship).success(successPostCallback).error(errorCallback);
};

$scope.ship不包含任何图像,当我调试它时开始上传它们,但不等待它完成并只执行下一行代码。

如何使其正常工作以确保$scope.uploadImages功能在继续之前完成?

1 个答案:

答案 0 :(得分:1)

为确保您的功能已完成,您需要使用promises

这是一个非常有用的视频教程,解释了如何使用它们:

https://egghead.io/lessons/angularjs-promises