I currently have the problem that my JS is reaching the end of my functions before all database calls have fulfilled. Which causes my function to return an incomplete dataset.
I've now tried async/await and Promise.then(). Now i'm mixing both but i don't get my function to wait until everything is done.
That's my code:
async function fillData(dashboards) {
let mapDashboards = await new Promise((resolve) => {
dashboards.map(async (dashboard) => {
if (dashboard.widgets) {
await dashboard.widgets.map(async (widget) => {
if (widget.panels) {
await widget.panels.map(async (panel) => {
if (panel.tabs) {
await mapPanelTabs(panel).then((tabs) => (panel.tabs = tabs));
}
});
}
});
}
});
console.log(dashboards);
resolve(dashboards);
});
return mapDashboards;
}
function mapPanelTabs(panel) {
return new Promise((resolve) => {
if (panel.tabs) {
var tabs = [];
panel.tabs.forEach(async (tab, index) => {
const dbTab = await Tab.findById(tab.id)
.clone()
.catch((e) => console.log(e));
if (dbTab) {
console.log("dbtab found");
tab = {};
if (dbTab.queryData && dbTab.queryData.id) {
await dataController
.findById(dbTab.queryData.id)
.catch((e) => console.log(e))
.then((queryData) => {
if (dbTab.type === "chart") {
// Some more logic
tabs[index] = tab;
});
}
} else {
tabs[index] = null;
}
});
resolve(tabs);
}
});
}
I need to get the promise in fillData to wait with the resolve until mapPanelTabs is done with the mapping.
Does anyone have an idea how to get this working?
Thanks in advance.