0

how can I await this nc.request and send the result

here is my post code

app.post('/sum',(req,res)=> {

    let result   
    nc.request('my.request', {x: 2, y:3 }, {max: 1}, resp => {
        console.log("Response from subscriber: " + resp)
        result = resp
    })
    res.status(200).send(result)
    
})
Masih Mol.
  • 87
  • 1
  • 7

3 Answers3

1

It looks like you already have the result inside your nc.request callback, so you can likely send your response from inside that callback.

app.post('/sum',(req,res)=> {
    nc.request('my.request', {x: 2, y:3 }, {max: 1}, resp => {
        console.log("Response from subscriber: " + resp)
        // Send here, since you have the response
        res.status(200).send(resp)
    })    
})

However, if nc.request returns a Promise containing the response data, you can await it inside an async function.

app.post('/sum', async (req,res, next)=> {
    try {
        const result = await nc.request('my.request', {x: 2, y:3 }, {max: 1})

        console.log("Response from subscriber: " + result)
        res.status(200).send(result)
    }
    catch (err) {
        // Have express handle errors from the async function
        next(err)
    }

})
scupit
  • 704
  • 6
  • 6
  • 1
    Will `app.post` properly deal with promise rejections if you use an `async` function? – Bergi Dec 19 '20 at 20:33
  • Looks like it won't automatically, however [you can pass all caught errors to express next function](http://expressjs.com/en/guide/error-handling.html#catching-errors) in order to have express handle them like normal. Inside an async function, you can handle rejections from `nc.request` using try/catch just like normal. [See here](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await#Adding_error_handling) for details. I'll update the async function's code to reflect this. – scupit Dec 19 '20 at 20:48
  • Thanks for the edit! Alternatively you can [write a wrapper function to do this](https://stackoverflow.com/questions/41349331/is-there-a-way-to-wrap-an-await-async-try-catch-block-to-every-function/41350872#41350872) – Bergi Dec 19 '20 at 21:04
0

This way it should work:

app.post('/sum', async (req,res)=> {
    let result =  await nc.request('my.request', {x: 2, y:3 }, {max: 1});   
    res.status(200).send(result)
});
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
0

You need to move res.status(200).send(resp) into the callback function, because you can get the result of the request inside the callback function.

app.post('/sum',(req,res)=> {
    nc.request('my.request', {x: 2, y:3 }, {max: 1}, resp => {
        console.log("Response from subscriber: " + resp)
        res.status(200).send(resp)
    })
})
Prime
  • 2,809
  • 1
  • 7
  • 23