Promise 无法正常工作saveService在 promise 解决之前被调用意味着所有文档都已上传,但是当我在saveService中记录数据时,它显示上传的文档无法找出问题,请让我知道我错在哪里
//file upload
$scope.fileObj = {};
$scope.documentUploaded = [];
var uploadFile = function (type) {
var file = $scope.fileObj[type];
//service to upload file
fileService.uploadDocument(file)
.success(function (data, status) {
console.log("uploaded successfully", data);
$scope.documentUploaded.push({
doc: {
fileName: data.name,
path: data.path
}
});
})
.error(function (data, status) {
});
}
$scope.save = function () { //on click of submit, save() is called
var defer = $q.defer();
var promises = [];
//looping to upload files
angular.forEach($scope.documentList, function (doc) {
if ($scope.fileObj[doc.type]) {
promises.push(uploadFile(doc.type));
}
});
//this will save data when promise will get complete
var saveData = function () {
var dataToSave = {
//other fields
documents: $scope.documentUploaded
};
saveService.saveApi(dataToSave)
.success(function () {
defer.resolve('data saved');
})
.error(function () {
defer.reject("something went wrong");
});
}
$q.all(promises).then(saveData);
return defer;
}