Javascript 角度异步函数不';Don’不要等到完成了才继续
我有一个上传功能,可以循环选择的文件并将它们添加到服务器文件系统中 上传功能:Javascript 角度异步函数不';Don’不要等到完成了才继续,javascript,angularjs,Javascript,Angularjs,我有一个上传功能,可以循环选择的文件并将它们添加到服务器文件系统中 上传功能: $scope.uploadImages = function () { for (var i = 0; i < $scope.imageModels.length; i++) { var $file = $scope.imageModels[i].file; (function (index) { $upload
$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.ship
不包含图像,当我调试时,它会开始上传图像,但不会等待图像完成,只执行下一行代码
我如何才能使其工作?因此,我要确保在继续之前完成
$scope.uploadImages
功能?为了确保您的功能完成,您需要使用
下面是一个非常有用的视频教程,介绍如何使用它们:
您错误地使用了AJAX。如果上载是异步的,则
$scope.uploadImages()
将永远不会以您期望的方式返回值。在.success
或.error
回调期间,您需要调用另一个函数。我从这篇文章中找到了答案:
$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);
};