[英]How can i extract values from promise and send them to client via node.js server?
I have a promise that returns data and I want to pass values of the promise as a response to client(web browser).我有一个返回数据的承诺,我想将承诺的值作为对客户端(网络浏览器)的响应传递。 I know i should probably use asynchronous js, but I'm not sure how to do that.
我知道我可能应该使用异步 js,但我不知道该怎么做。 Could you please give me some advice?
你能给我一些建议吗?
Here is how it looks like:这是它的样子:
if(req.url === "/api/posts"){
res.writeHead(200, {"Content-Type": "application/json"})
let db = new AppDAO('./db/db.sqlite3')
const postsDb = new PostsRepository(db)
let posts = postsDb.getAll()
db.close()
console.log(posts)
res.end()
}
What you need is to build the response when the DB Promise
resolves您需要的是在 DB
Promise
解决时构建响应
postsDb.getAll().then(posts => {
console.log(posts)
res.send(posts)
}).finally(() => db.close())
Or if you want to use the modern syntax, and can declare the surrounding function as async
:或者,如果您想使用现代语法,并且可以将周围的函数声明为
async
:
try {
const posts = await postsDb.getAll()
console.log(posts)
res.send(posts)
} catch(e) {
// Handle database error
} finally {
db.close()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.