As map
is not aware of async functions you need to use something that is. One example is the Bluebird Promise.map
equivalent:
const getExpiringContents = async () => {
let businessUnits = Object.keys(contentFulSpaces);
// Use Promise.map here to convert each businessUnit entry into a record
let expiringContentsAllBU = await Promise.map(businessUnits, async (bu) => {
await getOnlyContentWhatsNewReport(bu, (err, result) => {
if (!result) {
console.log('No expiring contents found for WhatsNewSection');
return;
}
let expiringContentsByBU = {};
expiringContentsByBU['businessUnit'] = bu;
expiringContentsByBU['expiringContents'] = result;
return JSON.parse(JSON.stringify(expiringContentsByBU));
})
});
// As this may contain undefined elements, remove those
expiringContentsAllBU = expiringContentsAllBU.filter(e => e);
console.log('result', expiringContentsAllBU);
}
You could flatten this code a bit more if you made getOnlyContentWhatsNewReport
return a promise as it should instead of using a callback method. async
won't wait on callback methods so be sure that also returns a promise or this code won't wait properly.
A fully promisized version that's refactored a litlte more looks like this:
const getExpiringContents = async () => {
let businessUnits = Object.keys(contentFulSpaces);
let expiringContentsAllBU = await Promise.map(businessUnits, async businessUnit => {
let expiringContents = await getOnlyContentWhatsNewReport(businessUnit);
if (!expiringContents) {
console.log('No expiring contents found for WhatsNewSection');
return;
}
// Choosing names that match the output means you can use the destructuring operator
let expiringContentsByBU = {
businessUnit,
expiringContents
};
// A more formalized "clone" function could help here.
return JSON.parse(JSON.stringify(expiringContentsByBU));
});
// As this may contain undefined elements, remove those
expiringContentsAllBU = expiringContentsAllBU.filter(e => e);
console.log('result', expiringContentsAllBU);
}