gpt4 book ai didi

angularjs - 异步循环函数中的 Angular Promise

转载 作者:行者123 更新时间:2023-12-02 23:28:27 28 4
gpt4 key购买 nike

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

上传工厂

app.factory('uploadFactory', function ($upload, $q) {

var uploadFactory = {};

var image = {
Models: [],
Images: [],
uploadImages: function () {
var defer = $q.defer();
for (var i = 0; i < this.Models.length; i++) {
var $file = this.Models[i].file;
(function (index) {
$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: image.Models[index].Description,
Photographer: image.Models[index].Photographer
};
image.Images.push(imageObject);

defer.resolve(result);
});
})(i);
}
return defer.promise;
}
};

uploadFactory.image = function () {
return image;
};

return uploadFactory;
});

在我的 Controller 中

$scope.imageUpload = new uploadFactory.image;
$scope.create = function () {
var uploadImages = $scope.imageUpload.uploadImages();
uploadImages.then(function ()
$scope.ship.Images = $scope.imageUpload.Images;
shipFactory.create($scope.ship).success(successPostCallback).error(errorCallback);
});
};

我的问题是 promise 仅包含通过循环首次上传的 promise 。我读过一些关于 $q.all() 的内容,但我不确定如何实现它。

我怎样才能让它坚持整个循环?谢谢!

解决方案

var image = {
Models: [],
Images: [],
uploadImages: function () {
for (var i = 0; i < this.Models.length; i++) {
var $file = this.Models[i].file;
var defer = $q.defer();

(function (index) {
var promise = $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: image.Models[index].Description,
Photographer: image.Models[index].Photographer
};
image.Images.push(imageObject);

defer.resolve(result);
});
promises.push(promise);
})(i);
}
return $q.all(promises);
}
};

最佳答案

你是对的 $q.all() 是去这里的方法(完全未经测试 - 但我认为这至少是正确的方向..):

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;
});

关于angularjs - 异步循环函数中的 Angular Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903453/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com