简体   繁体   中英

Get to response in Express in a promise?

So I have some code with Express :

let promiseLink = new Promise(function(resolve, reject) {
    app.post('/recipes', (req, res) => {
        resolve(req.body.linkText)
    })
})
promiseLink.then(function(value) {
    /* some code that I can't show, but is not much */
    .end(function (result) {
        let result = result.body
    }) 
})

Now, my question is, is there a way to get to the response of the post function from the .end(function).. block? Furthermore, if there is, I want to send raw html code, what would be the best way to do that? If there is not a way to get to the response, can I restructure my code so that I can?

In your Promise, you can resolve() with any value you want. Just add the response, such as:

app.post('/recipes', (req, res) => {
    resolve({linkText: req.body.linkText, response: res})
})

The .then() value will be this object, or however you choose to structure it.

Something like this should work:

let promiseLink = new Promise(function(resolve, reject) {
    app.post('/recipes', (req, res) => {
      resolve({response: res, linkText: req.body.linkText})
    })
})
promiseLink.then(function({response, linkText}) {
    /* some code that I can't show, but is not much */
    .end(function(result) {
        // you can read response here now
        let result = result.body
    })
})

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