gpt4 book ai didi

javascript - Express.js : Empty object sent along with response

转载 作者:行者123 更新时间:2023-12-02 22:46:17 24 4
gpt4 key购买 nike

我有三个准备好的 SQL 语句要执行。一旦执行SQL语句,结果将被添加到响应对象中,然后发送到客户端。然后,响应显示一个空对象,尽管它应该在那里。我可能是错的,但我认为我的回答可能不正确。欢迎任何其他建议,因为我对 Node.js 还很陌生。

    const s1 = 'small sql statement'

const s2 = 'small sql statement'

const s3 = 'small sql statement'

var responseObject = {}

const onError = err => {res.send({error: err}); console.error(err)}
const updateResponse = results => {results.map((item) => {Object.assign(responseObject, item)})}
const statements = [s1, s2, s3]

router.get('/stats', (req,res,next) => {
statements.map((statement) => {
con.query(statement, (err,results) => {
if (err) onError(err);
updateResponse(results);
})
})
res.send({
success: responseObject
})
})

module.exports = router;

最佳答案

您将在数据库查询完成之前发送响应。

您可以使用 promise 来处理此问题:

const s1 = 'small sql statement'

const s2 = 'small sql statement'

const s3 = 'small sql statement'

const statements = [s1, s2, s3]

router.get('/stats', (req, res, next) => {

// Generate array of promises
const promises = statements.map(statement => {
return new Promise((resolve, reject) => {

con.query(statement, (err, results) => {
if (err) reject(err);
resolve(results);
});

});
});

// Wait for all promises to resolve
Promise.all(promises)
.then(results => {

// Merge results into single object
const responseObject = results
.flat()
.reduce((acc, cur) => Object.assign(acc, cur), {});

res.send({ success: responseObject });
})
.catch(err => {
res.send({ error: err });
console.error(err);
});

});

module.exports = router;
<小时/>

如果您的 Node 版本不支持 .flat() 那么您可以修改为:

const responseObject = [].concat.apply([], results)
.reduce((acc, cur) => Object.assign(acc, cur), {});

关于javascript - Express.js : Empty object sent along with response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com