我無法控制我的方法的使用承諾的流程:嵌套承諾控制流量在循環
//FIND CHECKED OUT FILES
getCheckedOutFiles = function() {
console.log('Get checked out files');
var d = $q.defer();
// Store final results and pass to then callback
var checkedOutFiles = window.x = [];
// Promise, returns collection with all sites
SiteService.getAllSites()
.then(sites => {
// For each site get lists then get items matching filter
sites.forEach(function (site) {
var web = new $pnp.Web(site.url);
return web.lists
.filter("BaseTemplate eq 101")
.get() // Returns promise with all lists matching filter
.then(lists => {
// Go through each list and find matching item
lists.forEach(function (list) {
web.lists.getByTitle(list.Title).items
.filter("CheckoutUser ne null")
.expand("File, File/Author, File/ModifiedBy, File/CheckedOutByUser")
.get() // Returns promise with all items matching filter
.then(files => {
// Loop through each item, get properties, add to collection
files.forEach(function (f) {
var fileObject = {
fileName: f.File.Name,
fileUrl: f.File.ServerRelativeUrl,
absoluteUrl: f.File.ServerRelativeUrl,
checkedTo: f.File.CheckedOutByUser.Title,
modified: f.Modified,
modifiedBy: f.File.ModifiedBy.Title,
createdBy: f.File.Author.Title,
created: f.Created,
version: f.File.UIVersionLabel
};
// Add file to collection
checkedOutFiles.push(fileObject);
}, this);
})
.catch(e => {
console.log(e);
});
});
// "Ideally" - When all files retrieved return collection of results
d.resolve(checkedOutFiles);
return null;
})
.catch(e => {
console.log(e);
});
}, this);
return null;
});
return d.promise;
};
// Returns promise with all checkedout file
getCheckedOutFiles().then(files => {
console.log("RESULTS", files);
d.resolve(files);
});
我注意到了console.log("RESULTS", files);
會打印出完成調用之前。呼叫完成後,window.x
將包含預期數據。
還有比你顯示需要解決這個問題。 'site.forEach()'中的return()。web.lists.filter()。get()。then()'並不等待這個承諾。 – jfriend00
另外,這是一個承諾[反模式](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)與OP的'd.resolve()',其中不需要包裝所有這一切在另一個承諾。 – jfriend00