在以下代码中,expiringContentsAllBU
填充在 array.map()
内部的异步/等待函数 getOnlyContentWhatsNewReport
中,但在 businessUnits.map()
函数外部访问时 expiringContentsAllBU
会变为空。
const getExpiringContents = async () => {
let businessUnits = Object.keys(contentFulSpaces);
let expiringContentsAllBU = [];
businessUnits.map( async (bu) => {
await getOnlyContentWhatsNewReport(bu, (err, result) => {
if(result) {
let expiringContentsByBU = {};
expiringContentsByBU['businessUnit'] = bu;
expiringContentsByBU['expiringContents'] = result;
expiringContentsAllBU.push(JSON.parse(JSON.stringify(expiringContentsByBU)));
} else console.log('No expiring contents found for WhatsNewSection');
})
});
console.log('result', expiringContentsAllBU);
}
最佳答案
var getOnlyContentWhatsNewReport = Promise.resolve(123);
const getExpiringContents = async () => {
let businessUnits = [{ id: 1 }, { id: 2 }, { id: 3 }];
const expiringContentsAllBU = await Promise.all(businessUnits.map(async (bu) => {
return getOnlyContentWhatsNewReport.then(respBu => {
bu.businessUnit = respBu;
return bu;
}).catch((err) => {
console.log('No expiring contents found for WhatsNewSection');
return null;
});
}));
console.log('result', expiringContentsAllBU);
}
getExpiringContents();
您必须等到映射完成且所有回调完成。 console.log
和后续代码块将在 map 完成之前执行,因此
const getExpiringContents = async () => {
let businessUnits = Object.keys(contentFulSpaces);
const expiringContentsAllBU = await Promise.all(businessUnits.map(async (bu) => {
return getOnlyContentWhatsNewReport(bu, (err, result) => {
if(result) {
let expiringContentsByBU = {};
expiringContentsByBU['businessUnit'] = bu;
expiringContentsByBU['expiringContents'] = result;
return JSON.parse(JSON.stringify(expiringContentsByBU);
} else {
console.log('No expiring contents found for WhatsNewSection');
return null;
}
})
}));
console.log('result', expiringContentsAllBU);
}
关于javascript - async/await 不会将构建的数组返回到父 array.map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834513/