在Express.js中为什么res.json()之后的代码仍然执行? [英] In Express.js why does code after res.json() still execute?

查看:107
本文介绍了在Express.js中为什么res.json()之后的代码仍然执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Node with Express中,我有一段这样的代码。

In Node with Express, I have a piece of code like this.

 if (req.body.var1 >= req.body.var2){
        res.json({success: false, message: "End time must be AFTER start time"});
        console.log('Hi')
 }
 console.log('Hi2')
 //other codes

我预计如果var1> = var2,将发送响应并执行结束。像Java / C#中的return语句

I expected that if var1 is >= var2, the response would be sent and the execution would end. Like return statements in Java/C#

但是看起来并非如此。发送响应后,Hi和Hi2以及之后的所有其他代码继续执行。

But appearantly that's not the case. After the response is sent, both 'Hi' and 'Hi2' and all the other code after that continues to get executed.

我想知道如何阻止发生了什么?

I was wondering how I would stop this from happening?

此外,我想知道在什么情况下你真的希望代码在响应已经发送后继续执行。

Also, I was wondering under what circumstances would you actually want code to keep on executing after a response has already been sent.

干杯

推荐答案

Express只调用匹配路线的JavaScript函数。当函数完成/不完整时,没有特别的魔力可知。它只是运行该功能。但是,只要你想要退出函数就很容易...

Express just calls a JavaScript function for the matched route. There's no special magic to know when the function is complete/incomplete. It just runs the function. However, it's very easy to exit the function whenever you want...

你可以使用 return 来停止执行快递中特定路线的回调。它只是JavaScript ......该函数将始终尝试运行完成

You can use return to stop executing the callback for a specific route in express. It's just JavaScript... the function will always attempt to run to completion

app.post('/some/route', (req, res)=> {
  if (req.body.var1 >= req.body.var2){
    // note the use of `return` here
    return res.json({success: false, message: "End time must be AFTER start time"});
    // this line will never get called
    console.log('Hi')
  }
  // this code will only happen if the condition above is false
  console.log('Hi2')
  //other codes
});

关于字符串比较的警告

您正在使用

req.body.var1 >= req.body.var2

所有HTML表单值都以字符串形式发送到服务器。

All HTML form values are sent to the server as strings.

// javascript string comparison
"4" > "3"  //=> true
"4" > "30" //=> true
parseInt("4", 10) > parseInt("30", 10) //=> false

我确信你需要进行更有教育的比较。看起来他们是时间价值?因此,您可能希望将这些值转换为 Date 对象并进行准确比较。

I'm certain you'll need to make a more educated comparison than that. It looks like they're time values? So you'll likely want to convert those values to Date objects and do an accurate comparison.

这篇关于在Express.js中为什么res.json()之后的代码仍然执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆