The below data
function is called by a get route. The problem I have is that I can't figure out why the images
array remains empty on return images
but shows as correctly populated at console.log(images)
in my recursive start(node)
function -- which performs a DFS by repeatedly calling the Microsoft Graph API and allocates img
objects to the images
array. I initialise the traversal after res
contains the object tree.
I assumed that return images
would execute only after the recursion is complete and images
is populated, but that doesn't look to be the case. I think it's an asynchrony issue which I'm not too familiar with, so would appreciate any help or solution.
shelfdb.data = (accessToken) => {
const token = accessToken;
const endpoint = 'https://graph.microsoft.com/v1.0/sites/webgroup.sharepoint.com,23e7ef7a-a529-4dde-81ba-67afb4f44401,0fa8e0f7-1c76-4ad0-9b6e-a485f9bfd63c/drive/items/01GNYB5KPQ57RHLPZCJFE2QMVKT5U3NYY3/children'
var res = callMsGraph(token, endpoint);
var images = []
function start(node) {
if(node.value) {
node.value.forEach(function(child) {
var end = 'https://graph.microsoft.com/v1.0/sites/webgroup.sharepoint.com,23e7ef7a-a529-4dde-81ba-67afb4f44401,0fa8e0f7-1c76-4ad0-9b6e-a485f9bfd63c/drive/items/' + child.id + '/children';
var result = callMsGraph(token, end);
result.then(function(result) {
if (result.value.length > 0) {
if ('image' in result.value[0]) {
result.value.forEach(function(imgChild) {
let img = {
'name': imgChild.name,
'job': imgChild.parentReference.path.split("/")[6],
'path': imgChild.webUrl
}
images.push(img);
console.log('images object:')
console.log(images);
})
return;
}
}
start(result);
})
})
}
}
res.then(function(result) {
start(result);
})
return images;
};