我的Angularjs应用程序有一个控制器和服务java脚本。服务使用$ http调用WCF REST服务。我需要根据For循环中使用的对象中的数据在For循环中调用多个服务。以下是场景:
“我想将几个文件上传到服务器上的文件夹并将文件名保存到数据库。我有一组用户选择上传的文件详细信息。我想验证数据库中已有的文件名(基于EntityId)然后在上传到服务器之前重命名新文件。“以下是for循环和服务调用:
for (var i = 0; i < filesDataToUpload.length; i++) {
var fileDataToUpload = filesDataToUpload[i];
FileUploadService.GetUploadDetailsByEntityId(fileDataToUpload.ENTITY_ID).success(function (response) {
$scope.UploadDetailsByEntity = response;
});
var newFileName = VerifyAndRenameBeforeSave(fileDataToUpload, $scope.UploadDetailsByEntity);
FileUploadService.UploadFile(newFileName, fileData).success(function (data) {
//some code
}).error(function (error) {
$scope.error("An error occured while uploading file -" + error.ExceptionMessage);
isSuccess = false;
});
FileUploadService.InsertUploadDetails(FileUploadDetails).success(function (data) {
//some code
}).error(function (error) {
$scope.error("An error occured while creating the Entity -" + error.ExceptionMessage);
isSuccess = false;
});
}
问题: 问题:
我的问题是 - 我没有得到第一次服务调用的响应,我希望在后续验证和重命名文件并保存到数据库的方法中使用。我发现这是因为$ http的承诺行为。所以我移动了文件验证和重命名方法,并在
中保存了部分功能.success(function(response){
//verify that file does not already exists and rename it to the next number of file
//upload the file to the server
//Save new file name and other details to the database
}
但它只适用于第一次,而不是for循环的下一次迭代。对于第二次迭代,它将检索第一个EntityId的记录。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
它正在发生,因为 .success 函数在实际等待异步任务的响应时返回一个promise。试试这样 -
for (var i = 0; i < filesDataToUpload.length; i++) {
var fileDataToUpload = filesDataToUpload[i];
FileUploadService.GetUploadDetailsByEntityId(fileDataToUpload.ENTITY_ID).success(function (response) {
$scope.UploadDetailsByEntity = response;
var newFileName = VerifyAndRenameBeforeSave(fileDataToUpload, $scope.UploadDetailsByEntity);
FileUploadService.UploadFile(newFileName, fileData).success(function (data) {
//some code
FileUploadService.InsertUploadDetails(FileUploadDetails).success(function (data) {
//some code
}).error(function (error) {
$scope.error("An error occured while creating the Entity -" + error.ExceptionMessage);
isSuccess = false;
});
}).error(function (error) {
$scope.error("An error occured while uploading file -" + error.ExceptionMessage);
isSuccess = false;
});
});
}