从异步,用延时来处理,改成同步获取数据
获取数据主要分2步:
1.从redis集合中获取数组;
2.遍历数组,抓取其中字符串,解析,拼接成需要的数据,返回给前端
原代码,用sleep方法,避免异步数据处理带来的提前返回数据的问题;
- (缺点:时间比较久,逻辑中是有问题的)
// 获取线路上公交的位置信息
app.post("/bus/getLineBusPos",async (req,res)=>{
const { lineCode } = req.body;
if(!lineCode){
res.send({ret: 101, msg: '缺少线路参数'})
return;
}
let data = await getredisdata(lineCode);
await sleep(888); // 休眠 2 秒
res.send({ret: 0, msg: '获取成功',data})
return;
})
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const getredisdata = async(lineCode) => {
let shangxing = [],
xiaxing = [];
redisclient.smembers('xzspj_line_' + lineCode, (err, bus_arr) => {
console.log('-------all,sets,bus_arr----------');
console.log(bus_arr); // 输出集合中的所有元素
bus_arr.forEach((item) => {
//console.log(item)
redisclient.get('xzspj_bus_' + item, function(err, res){
let businfo = JSON.parse(res);
console.log("get bus callback:" , businfo)
if(businfo){
//从主站开往副站为下行,从副站开往主站为上行
if(businfo.status == 0 || businfo.status == 4){
console.log('--shangxing');
shangxing.push(businfo)
}
if(businfo.status == 2 || businfo.status == 3){
xiaxing.push(businfo)
}
}
});
})
});
let data = {};
data.shangxing = shangxing;
data.xiaxing = xiaxing;
return data;
}
优化后的代码
- 封装2个new Promise返回的方法
- for(const i of arr) 循环中才可以用 await,类似:forEach,each,map循环中不好放await
// 获取集合内容
function getSetContents(setName) {
return new Promise((resolve, reject) => {
// 以同步方式获取集合内容
redisclient.smembers(setName, (err, members) => {
if (err) {
reject(err);
} else {
resolve(members);
}
});
});
}
// 获取字符串内容
function getStrContents(strName) {
return new Promise((resolve, reject) => {
// 以同步方式获取集合内容
redisclient.get(strName, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
const getredisdata = async(lineCode) => {
let shangxing = [],
xiaxing = [];
try {
const members = await getSetContents('xzspj_line_' + lineCode);
console.log('members',members);
for(const item of members){
try {
let res = await getStrContents('xzspj_bus_' + item);
let businfo = JSON.parse(res);
console.log("get bus callback:" , businfo)
if(businfo){
//从主站开往副站为下行,从副站开往主站为上行
if(businfo.status == 0 || businfo.status == 4){
//console.log('--shangxing');
shangxing.push(businfo)
}
if(businfo.status == 2 || businfo.status == 3){
xiaxing.push(businfo)
}
}
} catch(err){
console.log('err2-->',err);
}
}
let data = {};
data.shangxing = shangxing;
data.xiaxing = xiaxing;
return data;
} catch(err){
console.log('err1---->',err);
} finally{
}
return;
}
// 获取线路上公交的位置信息
app.post("/bus/getLineBusPos",async (req,res)=>{
const { lineCode } = req.body;
if(!lineCode){
res.send({ret: 101, msg: '缺少线路参数'})
return;
}
let data = await getredisdata(lineCode);
//await sleep(888); // 休眠 2 秒----不用了
res.send({ret: 0, msg: '获取成功',data})
return;
})
相信坚持的力量,日复一日的习惯.