我被困了几个小时,无法将文件数组上传到我的服务器。我需要上传这个数组,然后使用这个文件数组作为参数上传一个对象。我的服务器将服务器端上传的文件名作为响应发回给我。我对 promise 的使用感到困惑,因为我得到了错误:
Cannot read property 'then' of undefined
这是我的代码:
function uploadImage(formData){
var deferred = $q.defer();
Image.aadd(formData).then(function(data){
deferred.resolve(data.data.fileName);
return deferred.promise;
});
}
function uploadImages(gallery){
var myGallery = [];
angular.forEach(gallery, function (image) {
var formData = new FormData();
formData.append('file', image);
var promise = uploadImage(formData);
promise.then(function(data){
myGallery.push(data.fileName);
});
});
var mygallery = uploadImages($scope.stock.gallery);
// Then use mygallery ["imgName1.png","imgName2.jpg", ... ]
最佳答案
uploadImage()
应该返回一个 promise ,以便有一个 then()
函数。此外,您可以简化直接返回值的 promise 。
When you return a value inside
then()
, this value will be passed to the first chained promise.
function uploadImage(formData) {
return Image.add(formData).then(function(data) {
return data.data.fileName;
});
}
然后,您应该重新组织您的 uploadImages()
函数。我建议采用以下方式。
function uploadImages(gallery) {
var uploadPromises = gallery.map(function(image) {
var formData = new FormData();
formData.append('file', image);
return uploadImage(formData);
});
return Promise.all(uploadPromises);
}
uploadImages($scope.stock.gallery).then(function(mygallery) {
// then you should use mygallery
});
说明:您应该将所有上传 promise 放入一个数组中。使用 Promise.all
,您可以捕捉到所有上传完成的时刻。然后,通过 then()
创建一个包含所有可用文件名的数组。
关于javascript - Imbrication promise 上传文件 angularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277846/