I apologize for the lackluster title, but I couldn't come up with anything more suitable. If this issue has already been addressed, please let me know in the comments and I will delete it promptly. However, keep in mind that this is a specific question.
Explanation: There is an API call that retrieves data from the server (an array) which then initiates a loop. Within this loop, another API call based on the parent index (child makes API call using parent index) fetches data and maps it into an array. A callback needs to be called after the last child of the last parent completes its task.
Mimic code:
for(let i=0;i<2;++i){
for(let j=0;j<2;++j){
map data into another array with predefined shape
console.log(i +", "+ j)
}
}
console.log('good to go for callback');
Desired outcome
0, 0
0, 1
1, 0
1, 1
good to go for the callback
Actual code:
var projects = api.getProjects(req);
projects.then(function(response){
response.projects.map(_e => {
var project = api.getProjectContent(_e.id);
project.then(function(_response){
_response.content.map(e=> {
global_array.push(...);
console.log('hello');
});
});
});
console.log('yellow');
});
I want to print "yellow" in the console exactly after every single child from every single parent has been added to an array (or get the length of the array).
What I've attempted so far:
var projects = api.getProjects(req);
projects.then(function(response){
Promise.all(response.projects.map(_e => {
var project = api.getProjectContent(_e.id);
project.then(function(_response){
_response.content.map(e=> {
global_array.push(...);
console.log('hello');
});
});
})).then(()=>{ console.log('yellow'); });
});
And
var projects = api.getProjects(req);
projects.then(function(response){
let pr = new Promise((resolve, reject) => {response.projects.map(_e => {
var project = api.getProjectContent(_e.id);
project.then(function(_response){
_response.content.map(e=> {
global_array.push(...);
console.log('hello');
});
});
})) });
pr.then(()=>{ console.log('yellow'); });
});
Plus, some additional attempts. Any typos in the above codes are insignificant because they were written in the SO editor, so there may be missing parentheses/curly braces. Further information: No errors have been encountered. If you believe there are better solutions aside from promises (such as async/await...), please feel free to share your insights.