问题背景
在处理数据的时候,经常需要拿到一个iXXXd再去XXX表里面查询,但是查询是异步操作。返回的数据中,newMatchInfo一直是空的
let newMatchInfo = matchInfo.map(async item => {
item.competionName = await acceptableMatchModel.query(`select competitionName from tb_competition where competitionId = '${item.competitionId}'`);
item.placeInfo = await acceptableMatchModel.query(`select * from tb_data_dictionary where itemKey = '${item.palceId}'`);
return item;
});
return this.success({
data: newMatchInfo,
pageNo,
pageSize,
total: total[0].totalNum
});
分析与解决
- 分别打印item和newMatchInfo
发现item里面有数值,但是newMatchInfo里面没有,怀疑是异步原因 - 分析:
因为async函数返回的是一个Promise,所以map返回的是Promise数组。我必须等到所有Promise得到处理之后再进行赋值操作。 - 解决:
通过await Promise.all(arrayOfPromises)解决
最终代码
let newMatchInfo = matchInfo.map(async item => {
item.competionName = await acceptableMatchModel.query(`select competitionName from tb_competition where competitionId = '${item.competitionId}'`);
item.placeInfo = await acceptableMatchModel.query(`select * from tb_data_dictionary where itemKey = '${item.palceId}'`);
return item;
});
newMatchInfo = await Promise.all(newMatchInfo);
return this.success({
data: newMatchInfo,
pageNo,
pageSize,
total: total[0].totalNum
});