简体   繁体   English

Express.js 在 promise.catch() 错误中发送响应

[英]Express.js sending response in promise .catch() error

I have a function that looks like this:我有一个看起来像这样的 function:

function x(req, res, next){

    await doSomething().catch(error =>{

        return res.send('error here'})

        }
    await doSomethingElse().catch(error =>{console.log(error)})

    return res.send('success');

}

When doSomething() returns an error, I get "Cannot set headers after they are sent to the client", which I understand, but why doesn't the script terminate when I call the first res.send?当 doSomething() 返回错误时,我得到“在将标头发送到客户端后无法设置标头”,我理解,但是为什么在我调用第一个 res.send 时脚本没有终止?

My guess is that it's similar to a callback in that the returned value is ignored, so it sends the response, but ignores the fact that the script should end there.我的猜测是它类似于回调,因为返回的值被忽略,所以它发送响应,但忽略了脚本应该在那里结束的事实。

How can I fix this problem?我该如何解决这个问题?

It gets very complicated to control flow when you are mixing .catch() and await .当您混合.catch()await时,控制流程变得非常复杂。 I would strongly suggest using only one model at a time.我强烈建议一次只使用一个 model。 With await, you can do this:使用 await,您可以执行以下操作:

async function x(req, res, next) {
    try {
        await doSomething();
        await doSomethingElse();
        res.send('success');
    } catch(e) {
        console.log(e);
        res.send('error here'})
    }
}

why doesn't the script terminate when I call the first res.send?为什么当我调用第一个 res.send 时脚本没有终止?

Because the return in that statement just returns back from the .catch() handler not from your main function and since you've done a .catch() and not thrown inside that catch handler or returned a rejected promise from the handler, then the parent promise because resolved and execution after the await continues just fine which then causes you to run into the second res.send() which causes the warning about headers already sent.因为该语句中的return只是从.catch()处理程序返回,而不是从您的主 function 并且由于您已经完成了.catch()并且没有在该 catch 处理程序中抛出或从处理程序返回被拒绝的 promise,所以父 promise 因为在await之后解析和执行继续正常,然后导致您遇到第二个res.send() ,这会导致有关已发送标头的警告。

if you want to use .then() .catch() just try:如果你想使用 .then( .then() .catch()试试:

function x(req, res, next) {
  doSomething()
    .catch((error) => {
      return res.send("error here");
    })
    .then(() => {
      doSomethingElse()
        .catch((error) => {
          console.log(error);
        })
        .then(() => {
          return res.send("success");
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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