【发布时间】:2017-06-10 15:45:57
【问题描述】:
在我正在开发的 AngularJS 应用程序中,我尝试异步处理多个上传的文件,以便为将它们添加到 SuiteCRM 实例的例程做好准备。总体而言,代码没有错误,但我发现延迟调用一个接一个地执行,并且在解决所有承诺之前不会将结果传递给等待脚本。也许有人可以帮助我解决如何链接这些以获得我想要的结果?
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);
});
});
}
}
};
所以,你看,我需要 FileReader 来处理文件,返回文件的内容,以便将它传递给 $scope.fileList 中每个 f(文件)的 createNewUploadedDocument 函数。 NGF 的多文件选项对我不可用,因为每个文件都有特定的模板类型和描述。
您可以提供或建议的任何帮助将不胜感激。
编辑 - 我已阅读此Chaining multiple promises created through for loop 和此angular $q, How to chain multiple promises within and after a for-loop,但都没有针对我的具体情况提供任何有用的反馈。我知道可以使用 $q.all 嵌套和组合承诺,但它们仍然可以相互提供结果数据吗? 我的内部方法是调用 REST API - 并不是说它有任何区别 - 但我确实需要 FileReader 承诺的结果才能调用它。
【问题讨论】:
-
什么部分不起作用?代码有点乱,但应该可以工作,但是由于您不太清楚您想要的结果是什么,所以很难提供帮助。
-
在调用底层函数之前,它会遍历所有的 fileReader 承诺。
-
这是不可能的。当第一个承诺从
fileReader解决时,它应该继续到第一个.then()。没有什么可以阻止它继续,所以在输入任何.then()之前它会等待所有承诺的情况是不合逻辑的。 -
我已经控制了这个输出,它确实做到了——遍历每个
fileReader,然后只提供最后一个result给.then()。看起来可能不合逻辑(而且我认为代码也应该像编写的那样工作)!
标签: angularjs asynchronous promise filereader deferred