莱姆解释:
问题:
我需要返回一个带有如下对象的数组:
[
{
region: region,
towns: [multiple towns]
},
{
region: region,
towns: [multiple towns]
},
{
region: region,
towns: [multiple towns]
}
]
此刻,正在返回一个空数组[]
。
这是我的代码:
serve.get('/info', cors(corsOptions), (req,res)=>{
let result=[]; //create array to store data
dbConn.query(
`SELECT DISTINCT region FROM address region`, //first query
(error, rows)=>{
if(!error){// BEGIN IF FOR FIRST QUERY
// WHEN THERE IS NO ERROR
for(let i=0; i<rows.length; i++){// iterate trough result and get all towns in that region
let region= rows[i].region;
dbConn.query(
'SELECT DISTINCT town FROM address WHERE region=? ORDER BY town',// SECOND QUERY
[region],// GET TOWNS OF CURRENT REGION
(error, rows)=>{
if(!error){// IF FOR SECOND QUERY
//when there is no error
result.push({divnum: division, blocks: rows})// push details into array in desired format
}else{// END IF
//when there is an error
saveError(error);// FUNCTION TO LOG ERROR
res.send(error);
}// END ELSE
}// END CALLBACK
);
}// END FOR-LOOP
res.send(result);// Send result
}else{// END IF FOR FIRST QUERY
// WHEN THERE IS AN ERROR
saveError(error);
res.send(error);
}
}
)
});//END SERVE
我确实意识到将返回一个空数组,因为程序在执行任何操作之前并未完全等待查询的任何结果。
为了获得所需的结果,我需要修改什么?
即:
[
{
region: region,
towns: [multiple towns]
},
{
region: region,
towns: [multiple towns]
},
{
region: region,
towns: [multiple towns]
}
]