Angular异步函数在继续之前不等待完成

3

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

上传功能:

$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函数已经完成?


你的AJAX使用方法不正确。如果上传是异步的,那么$scope.uploadImages()将永远不会以你期望的方式返回值。你需要在.success.error回调期间调用另一个函数。 - g.d.d.c
https://dev59.com/RGYq5IYBdhLWcg3wwDRA - Moob
我从这篇帖子中找到了答案: https://dev59.com/gmMl5IYBdhLWcg3wa2bV - Lars
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接