javascript - async/await 不会将构建的数组返回给父 array.map()
问题描述
在下面的代码中,expiringContentsAllBU
填充在 async/await 函数getOnlyContentWhatsNewReport
中,该函数位于 内部array.map()
,但expiringContentsAllBU
在函数外部访问它时变为空businessUnits.map()
。
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
代码块将在你的地图完成之前执行,所以
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);
}
推荐阅读
- heroku - 如何在 Heroku 上的 Rails 6 应用程序上设置 RAILS_PRODUCTION_KEY 配置变量
- swiftui - 如何调整选取器中的行大小?
- javascript - 仅当具有特定 id 的元素可用时才执行函数
- java - 如何从我的 Mac 卸载其他/较旧的 Java 版本?
- python - ERROR Connection in use: ('0.0.0.0', 5000) 启动 gunicorn 以在本地运行 python 应用程序 Heroku
- c# - 无法将“MySql.Data.MySqlClient.MySqlException”类型的对象转换为“System.IConvertible”类型。
- python - 如何打开和关闭 Tkinter 窗口?
- python - 如何使用 Python 计算一行和下一行之间的值(来自 csv 文件)
- python - Python 不一致问题 - Adafruit io
- azure - 如何在 Azure DevOps 中创建功能燃尽图?