简体   繁体   English

如何从 promise 中提取值并通过 node.js 服务器将它们发送到客户端?

[英]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.

相关问题 如何通过HttpUrlConnection将图像从Android客户端发送到Node.js服务器? - How to send an image from Android client to Node.js server via HttpUrlConnection? Node.js,Express:如何与客户端一起处理res.send值 - Node.js, Express: How can I handle res.send values with the client 如何将数据作为响应从Node.js服务器发送到AJAX客户端? - How do I send data as a response from Node.js server to AJAX client? 如何从我的 Node.JS 向我的 Javascript 客户端发送一个警报? - How can I send one alert from my Node.JS to my Javascript client? 在Node.js / Express.js中,如何将JSON对象从服务器传输到客户端? - In Node.js/Express.js, how can I transfer a JSON object from server to client? 通过功能调用将消息从Node.js服务器发送到客户端 - Send message from Node.js Server to Client via function call 如何通过node.js将可下载的pdf发送到javascript客户端? - How to send a downloadable pdf to javascript client via node.js? 如何从另一个 function 向连接到 Node.js 套接字服务器的客户端写入数据? - How can I write data to the client connected to a Node.js socket server from another function? 如何将数据从 javascript 发送到 node.js TCP 服务器? - How can I send data from javascript to a node.js TCP server? 如何将 CSV 从 React 应用程序发送到 Node.js 服务器? - How can I send CSV from React app to Node.js server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM