在项目中需要对connection.query中返回的数据进行循环处理,但是发现使用循环处理后
(error, row) => {
if (error) {
throw error;
} else {
row.map(el=>{
el.name=getuserInfo(el.id) //getuserInfo也是一个connection.query
})
res.json(data:row)
}
,res.json返回的数据还是原来的数据,row.map里面其实已经处理了,不过代码先执行了res.json,很是困扰。虽然使用了promise async await但还是没成功。后面看了这个https://blog.csdn.net/u011249920/article/details/54340234?%3E
解决方法:使用 async模块来处理
首先 npm install async
async模块文档地址:https://caolan.github.io/async/v3/docs.html#concat
(error, row) => {
if (error) {
throw error;
} else {
async.map(
row,
(el, callback) => {
el.name = "";
getUserInfo(el.id).then(res => {
el.name = res[0].name;
callback(null, el);
});
return el;
},
(err, result) => {
console.log(result);
res.json({ code: 200, data: result, msg: "查询成功" });
}
);
}