In the main function I want to call a series of functions that need to wait for the previous one to finish first.
I want my console to output: A, B, B, B, B, C, D. Where B would appear a few times for each item in snapPivot.
The result I get now is: A, C, D, B, B, B, B
It seems that the getPivot function is not waiting for the inner loop to finish. How can I make sure the getPivot function first finishes the inside loop with the console.log('b')
before continuing to console.log('c')
and console.log('d')
main function:
dashboardListner
.child(activeDashboardId)
.child('widgets')
.once('value', snap => {
widgets = snap.val();
})
.then(thenWidgets => {
async function asyncCall() {
console.log('A');
Object.entries(thenWidgets.val()).map(async function(widget) {
return await getPivot(widget, userId);
});
console.log('C');
}
return asyncCall();
})
.then(pivotData => {
async function asyncCall2() {
console.log('D');
return await getMain(pivotData);
}
return asyncCall2();
})
getPivot function:
const getPivot = (widget, userId) => {
return new Promise(resolve => {
const pivotData = {};
//Get get pivot table name
const pivotName =
'user' + widget[1].type.charAt(0).toUpperCase() + widget[1].type.slice(1);
//Get pivot data into widget object
const pivotRef = firebase
.database()
.ref()
.child(pivotName)
.child(userId);
pivotRef
.once('value', snapPivot => {
return Promise.all([
snapPivot.forEach(function(result) {
if (result.val().widgetId === widget[0]) {
pivotData[result.key] = result.val();
console.log('B');
}
}),
]);
})
.then(() => {
resolve(pivotData);
});
});
};