I'm trying to create a recursive function using Promises, but can't quite seem to get it right. I have working code without using promises, but it uses counters and global variables etc. and doesn't feel quite right, so I'm attempting a rewrite and also creating a module for reuse.
Essentially, the function is supposed to be getting a user from Active Directory and then recursively finding any direct reports and their direct reports and so on.
I've played with lots of versions of the function, this is the current one:
function loadReports(personEmail, list) {
return new Promise((resolve, reject) => {
getAccessTokenPromise()
.then(access_token => {
list.push(personEmail);
return makeRequest(personEmail, access_token);
}).then(result => {
if (result.value.length > 0) {
Promise.all(result.value.map(person => {
loadReports(person.userPrincipalName, list);
})).then(resolve());
} else {
resolve();
}
})
.catch(e => reject(e));
});
}
The getAccessTokenPromise
function performs a request for an access token and returns a promise for that. The makeRequest
function again just makes an https request for the user and their reports and returns a json object with the results as a Promise.
Any thoughts greatly received. Many thanks. D.