【问题标题】:Stop express function after a reply has already been sent已发送回复后停止快递功能
【发布时间】:2020-03-05 10:46:42
【问题描述】:

我对 .js 和 .ts 非常陌生,因此对 express.js 也是如此。我有以下几行代码:

    private post = async ( request: express.Request, response: express.Response, next:express.NextFunction) => 
{
    await this.myfunction(next) ? console.log("Do nothing") : console.log("end function/request/response");
    await this.anotherfunction();
    }

我的函数看起来像:

private myfunction = async (next: express.NextFunction): Promise<boolean> => {

let temp: boolean = false;

if(temp){
  return true;
} else {
  next(
      new HttpException(404, "just an example error")
    );
  return false;
}

HttpException 函数的构建如下:https://wanago.io/2018/12/17/typescript-express-error-handling-validation/

我的问题: 当我触发我的 post 函数时,this.myfunction 将被执行,并且“function/request/response”将被打印在控制台中。之后 this.anotherfunction() 将被执行。但是我希望如果我从 this.myfunction 返回 false ,那么 this.anotherfunction() 将不会在我的传入请求被停止/取消时执行,因为我已经在 this.myfunction()

我该怎么做?

【问题讨论】:

  • 那你为什么不发回回复res.send()
  • 我使用与以下相同的错误处理:wanago.io/2018/12/17/… 这给我发送了一个 response.send

标签: javascript node.js typescript express


【解决方案1】:

你能不干吗?

const result = await this.myfunction(next);
if(result) {
 await this.anotherfunction();
}

最好在最后发送res.send

【讨论】:

  • 然后我将不得不将我所有的逻辑放入 IF 循环中,我认为这不太好。也许我可以以某种方式检查是否已经发送了响应,如果是,那么它应该停止。问题是处理和发送来自我的 HttpException 的响应需要几毫秒
  • 你不能简单地做return res.send()吗?这将停止执行
  • 不,我不能,因为我已经在我的 HttpException 函数中发送了响应。我会得到一个错误:发送到客户端后无法设置标头
猜你喜欢
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2015-04-24
  • 2019-11-27
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多