使用结果在AngularJS中进行多个异步调用
在我正在开发的AngularJS应用程序中,我试图异步处理多个上传的文件,以便为将它们添加到SuiteRM实例的例程做好准备。总的来说,代码是没有bug的,但是我发现延迟的调用一个接一个地被执行,并且在所有承诺得到解决之前不会将结果传递给等待的脚本。也许有人可以帮助我如何将这些链接起来,以获得我想要的结果使用结果在AngularJS中进行多个异步调用,angularjs,asynchronous,promise,filereader,deferred,Angularjs,Asynchronous,Promise,Filereader,Deferred,在我正在开发的AngularJS应用程序中,我试图异步处理多个上传的文件,以便为将它们添加到SuiteRM实例的例程做好准备。总的来说,代码是没有bug的,但是我发现延迟的调用一个接一个地被执行,并且在所有承诺得到解决之前不会将结果传递给等待的脚本。也许有人可以帮助我如何将这些链接起来,以获得我想要的结果 function fileReader(file) { // perform async operation var deferred = $q.defer();
function fileReader(file) { // perform async operation
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function () {
deferred.resolve(reader.result.replace(/^(.*),/g, ""));
};
reader.readAsDataURL(file);
return deferred.promise;
}
$scope.uploadFiles = function () {
console.log('Starting uploads');
$scope.uploadClicked = true;
$scope.uploadProgress = {};
$applicationID = $('#application_id').val();
var tmpMerchData = SessionService.getMerchantData();
var isoID = SessionService.getISOID();
if ($scope.fileList && $scope.fileList.length) {
var $myFiles = $scope.fileList;
for (var f = 0; f < $myFiles.length; f++) {
var thisFile = $myFiles[f];
console.debug(thisFile);
fileReader(thisFile.file).then(function (result) {
ApplicationFactory.createNewUploadedDocument(thisFile, thisFile.templatetype, result, thisFile.description, $scope.userID, tmpMerchData.id, $applicationID, isoID).then(
function successCallback(response) {
if (response.data.status === 1) {
console.log("Document creation succeeded");
$scope.uploadProgress = {
'progress': 100,
'index': f
};
} else {
console.log("Document creation failed");
}
}, function errorCallback(response) {
console.debug("Error returned from createNewUploadedDocument", response);
});
});
}
}
};
函数文件读取器(文件){//执行异步操作
var deferred=$q.deferred();
var reader=new FileReader();
reader.onload=函数(){
deferred.resolve(reader.result.replace(/^(.*),/g,”);
};
reader.readAsDataURL(文件);
回报。承诺;
}
$scope.uploadFiles=函数(){
log(“开始上传”);
$scope.uploadClicked=true;
$scope.uploadProgress={};
$applicationID=$('#应用程序id').val();
var tmpMerchData=SessionService.getMerchantData();
var isoID=SessionService.getISOID();
if($scope.fileList&&$scope.fileList.length){
var$myFiles=$scope.fileList;
对于(变量f=0;f<$myFiles.length;f++){
var thisFile=$myFiles[f];
调试(这个文件);
fileReader(thisFile.file).then(函数(结果){
ApplicationFactory.createNewUploadedDocument(thisFile,thisFile.templatetype,result,thisFile.description,$scope.userID,tmpMerchData.id,$applicationID,isoID)。然后(
函数成功回调(响应){
if(response.data.status==1){
console.log(“文档创建成功”);
$scope.uploadProgress={
"进步":100,,
“索引”:f
};
}否则{
console.log(“文档创建失败”);
}
},函数errorCallback(响应){
调试(“createNewUploadedDocument返回的错误”,响应);
});
});
}
}
};
所以,你看,我需要FileReader来处理文件,返回文件的内容,以便将其传递给$scope.fileList中每个f(文件)的createNewUploadedDocument函数。NGF的“多个文件”选项对我不可用,因为这些文件中的每个文件都有特定的模板类型和说明
如果您能提供任何帮助或建议,我们将不胜感激
编辑-我已经阅读了这篇文章和这篇文章,但都没有针对我的具体情况提供任何有用的反馈。我知道承诺可以使用$q进行嵌套和组合,但它们仍然可以相互提供结果数据吗?
我的内部方法是对RESTAPI的调用——这并没有什么区别——但我确实需要FileReader承诺的结果才能调用它 您可以有效地使用$q服务。 当您使用$q.all()时,您传递了一个承诺数组,结果得到了一个按相同顺序排列的每个承诺的结果数组。 所以我们可以像这样重写您的代码:
if ($scope.fileList && $scope.fileList.length) {
var $myFiles = $scope.fileList;
var promisesFileReader = [];
var promisesUploadedDocument = [];
for (var f = 0; f < $myFiles.length; f++) {
var thisFile = $myFiles[f];
console.debug(thisFile);
promisesFileReader.push(fileReader(thisFile.file));
}
$q.all(promisesFileReader)
.then(function(results) {
//We loop on results and push all the UploadDocument promises with the correct result
for (var i = 0; i < results.length; i++) {
promisesUploadedDocument.push(ApplicationFactory.createNewUploadedDocument(thisFile, thisFile.templatetype, results[i], thisFile.description, $scope.userID, tmpMerchData.id, $applicationID, isoID));
}
$q.all(promisesUploadedDocument)
.then(
function successCallback(response) {
if (response.data.status === 1) {
console.log("Document creation succeeded");
$scope.uploadProgress = {
'progress': 100,
'index': f
};
} else {
console.log("Document creation failed");
}
},
function errorCallback(response) {
console.debug("Error returned from createNewUploadedDocument", response);
});
});
}
if($scope.fileList&&$scope.fileList.length){
var$myFiles=$scope.fileList;
var promisesFileReader=[];
var promisesUploadedDocument=[];
对于(变量f=0;f<$myFiles.length;f++){
var thisFile=$myFiles[f];
调试(这个文件);
push(fileReader(thisFile.file));
}
$q.all(承诺文件阅读器)
.然后(函数(结果){
//我们对结果进行循环,并将所有上传的文档承诺推送到正确的结果上
对于(var i=0;i
回答-此原始代码的更新版本修复了问题
请注意,已经实现了一个angular.forEach
,以及一些已清理的变量名和重用
$scope.uploadFiles = function () {
console.log('Starting uploads');
$scope.uploadClicked = true;
$scope.uploadProgress = {};
$applicationID = $('#application_id').val();
var tmpMerchData = SessionService.getMerchantData();
var isoID = SessionService.getISOID();
if ($scope.fileList && $scope.fileList.length) {
angular.forEach($scope.fileList, function (thisFile, f) {
console.log('Starting upload #', f);
fileReader(thisFile.file).then(
function (fileContents) {
ApplicationFactory.createNewUploadedDocument(thisFile, thisFile.templatetype, fileContents, thisFile.description, $scope.userID, tmpMerchData.id, $applicationID, isoID).then(
function successCallBack(response) {
if (response.data.status === 1) {
console.log('Document creation succeeded');
$scope.uploadProgress = {
'progress': 100,
'index': f
};
} else {
console.log('Document creation failed');
}
}, function errorCallback(response) {
console.debug('Error returned from createNewUploadedDocument ', response);
});
});
});
}
};
这将不起作用,因为您正在调用
$q.all
for循环中的每次迭代。您应该将$q.all
移动到循环之外,并在从文件阅读器
获得完整承诺数组时调用它一次。抱歉,这不起作用。它返回“results”f
的次数。每次都是一个越来越大的物体。对不起。您必须将$q.all重新请求从for循环中取出。循环允许将所有承诺推送到一个数组,然后您可以使用$q.all调用每个承诺。有什么部分不起作用?代码有点凌乱,但应该可以工作,但由于您不太清楚您想要的结果是什么,因此很难提供帮助。在调用底层函数之前,它会遍历所有fileReader承诺。这是不可能的。它应该在未来继续下去