简体   繁体   中英

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. 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

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 :

try {
    const posts = await postsDb.getAll()
    console.log(posts)
    res.send(posts)
} catch(e) {
    // Handle database error
} finally {
    db.close()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM