I have a main function that awaits and connects a few functions in parallel like this:
Main function:
console.log('A');
const pivotData = await Promise.all(
Object.entries(thenWidgets.val()).map(widget => {
getPivot(widget, userId)
console.log('B');
});
);
console.log('C');
console.log('D');
const mainData = await Promise.all(
pivotData.map(widget => getMain(widget))
);
console.log('F');
mainData.map(item => {
return (finalObject[item.widgetId] = item);
});
console.log('G');
The works fine until it hits mainData below console.log('D')
. It seems to not await the promise and skip right to console.log('F')
without waiting for the getMain function which hold console.log('E')
getMain() Function:
const getMain = widget => {
return new Promise(resolve => {
var requests = [];
const pivotData = {};
Object.keys(widget.pivot).map(item => {
const mainRef = firebase
.database()
.ref()
.child(widget['default'].type)
.child(item);
mainRef.once('value', snapMain => {
pivotData[item] = snapMain.val();
}).then(() => {
widget['main'] = pivotData;
console.log('E');
requests.push('test');
});
console.log('E2')
})
Promise.all(requests)
.then(() => {
console.log('E3');
resolve(widget);
})
.catch(error => console.log(`Error in promises ${error}`));
});
};
The expected outcome here is: 'E, E2, E, E2, E3' but what i get is 'E2, E2, E3' and then it returns the promise. Later, somewhere after all the promises have resolved i get 'E, E'. So the expected outcome for the whole thing should be 'A, B, C, D, E, E2, E, E2, E3, F, G' what I have now is 'A, B, C, D, E2, E2, E3, F, G, E, E'
It seems that the promise inside the Object.keys
inside getMain()
is not waiting for the mainRef.once
. Perhaps I am missing something.
My question here is: What is going wrong that the promise is not waiting for the getMain()
function?