微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在邮件中等待请求

如何解决在邮件中等待请求

我如何等待这个 nc.request 并发送结果

这是我的邮政编码

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)
    
})

解决方法

看起来您的 nc.request 回调中已经有了结果,因此您很可能可以从该回调中发送响应。

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)
    })    
})

但是,如果 nc.request 返回一个包含响应数据的 Promise,您可以在异步函数中等待它。

app.post('/sum',async (req,res,next)=> {
    try {
        const result = await nc.request('my.request',{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)
    }

})
,

这样它应该可以工作:

app.post('/sum',res)=> {
    let result =  await nc.request('my.request',{max: 1});   
    res.status(200).send(result)
});
,

需要将res.status(200).send(resp)移动到回调函数中,因为可以在回调函数内部得到请求的结果。

app.post('/sum',resp => {
        console.log("Response from subscriber: " + resp)
        res.status(200).send(resp)
    })
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。