在这个函数中,我应该从我的数据库(mariaDB)中获取一些数据,然后对该结果执行另一个查询。这一切都应该发送回前端
pool.getConnection()
.then(conn => {
conn.query(query)
.then((rows) => {
console.log(`=== Request from: ${req.query.hostname} (${req.query.ip}) at ${new Date().toISOString().replace("T", " ")} => (CORRECT)`);
rows = rows.map((item) => {
switch (expectedReturnType) {
case "multiple":
conn.query(`
SELECT utente.nome, utente.cognome
FROM creatore_compito
JOIN utente ON utente.id = creatore_compito.id_creatore
WHERE creatore_compito.id_compito = ${item.id}
`).then(rows => {
return Object.assign(item, {
"verifica": item["verifica"] === 0 ? "compito" : "verifica",
"creatori": rows
});
}).catch(err => {
return err;
});
break;
case "single":
return item["verifica"] === 0 ? "compito" : "verifica"
default:
throw new TypeError(`"${expectedReturnType}" is not a valid type for "expectedReturnType"`)
}
});
res.send(rows);
})
.catch(err => {
console.log(`=!= Request from: ${req.query.hostname} (${req.query.ip}) at ${new Date()} => (ERROR) ${err}`);
res.status(500).send(err);
})
.finally(() => {
conn.end();
})
})
.catch(err => {
console.log(`=!= Request from: ${req.query.hostname} (${req.query.ip}) at ${new Date()} => (ERROR) ${err}`);
res.status(500).send("connection error");
});
然而,我注意到
res.send()
是在.map()
执行结束之前执行的。我试过以不同的方式使用 await Promise.All()
但我找不到解决方案,因为结果总是 null