以下代码旨在递归检索文件夹中的文件。 $ q.all(docDefs)在第一个promise被解析时解析,即使docDefs数组显示多个未解析的promises(第一个promise表示状态为1,而数组中的所有其他表示状态为0)。
var getDocsAndFolders = function(siteUrl, rootFolderUrl) {
var deferred = $q.defer();
var documents = [];
var folders = [];
var docDefs = [];
var getDocs = function(folder) {
var def = $q.defer();
folders.push(folder);
$q.all([getDocuments(siteUrl, folder.ServerRelativeUrl), getFolders(siteUrl, folder.ServerRelativeUrl)])
.then(function(d) {
documents = documents.concat(d[0].data.d.results);
angular.forEach(d[1].data.d.Folders.results, function(rf) {
if (rf.ServerRelativeUrl.toLowerCase() != (rootFolderUrl + '/Forms')
.toLowerCase()) docDefs.push(getDocs(rf));
});
def.resolve();
});
return def.promise;
};
docDefs.push(getDocs({
Name: 'Library',
ServerRelativeUrl: rootFolderUrl
}));
$q.all(docDefs)
.then(function() {
deferred.resolve({
documents: documents,
folders: folders
});
});
return deferred.promise;
};