我试过在一个对象上封装两个查询响应,然后在函数返回上使用该对象
app.get('/gerais',(req,res) => {
const client = new Client();
const data = new Object();
client.connect()
.then(() => {
data.result1 = client.query('SELECT * FROM student');
data.result2 = client.query('SELECT * FROM adress');
return data;
})
.then((results) => {
console.log('results?',results);
res.render('geral-info',results);
});
});
但终端打印中的“结果”:
results? { result1: Promise { <pending> }, result2: Promise { <pending> } }
我该如何调整,以便这个“待定”可以填充每个查询中返回的实际字符串?
最佳答案
client.query()
返回一个 promise ,而不是查询的结果。因此,您需要知道该 promise 何时解析,以便您可以从 promise 中获取数据。
如果你有两个 promise (你做了)并且你想知道它们何时完成,你可以使用 Promise.all()
。这将返回一个新的 promise ,当其他 promise 都解决时,该 promise 将解决为一系列结果:
client.connect()
.then(() => {
return Promise.all([client.query('SELECT * FROM student'), client.query('SELECT * FROM adress')])
})
.then((results) => {
console.log('results?',results);
// res.render('geral-info',{something from the results});
});
关于javascript - 使用 Promise 返回多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51561689/