Поскольку map
не знает об асинхронных функциях, вам нужно использовать что-то, что есть. Одним из примеров является Bluebird Promise.map
эквивалент:
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);
}
Вы могли бы сгладить этот код немного больше, если бы вы заставили getOnlyContentWhatsNewReport
вернуть обещание, как и должно, вместо использования метода обратного вызова. async
не будет ждать методов обратного вызова, поэтому убедитесь, что также возвращает обещание, или этот код не будет ждать правильно.
A полностью обещанная версия, которая подверглась рефакторингу, выглядит примерно так:
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);
}