javascript - 如何处理nodejs中的大量条件匹配?

标签 javascript mysql node.js rest express

我正在用express js编写API,有一些条件,如果它们匹配,我会尝试响应数据。所以问题是,如果两个条件匹配,我的代码响应两次,我可以在发送一次后停止响应另一个条件吗?由于我是 PHP 出身,所以这个 Node js 逻辑确实不一样。

我仍然尝试使用 res.end(),但如果另一个条件匹配,它会继续响应。我无法编写简单的 if else 条件语句,因为存在不同类型的条件。

请看一下我的代码,如果你能帮我解决这个问题,非常感激。

exports.createBooking = (req, res) => {
// Save Order to Database
console.log("Processing func -> Create Booking");
// console.log(req.body);
const business_code = 'Test' + new Date("03/25/2015") + Math.floor(Math.random() * 9999999999999) + 1 ;
const locker_station_id = req.body.locker_station_id || '';
const reference_id = req.body.reference_id || '';
console.log(locker_station_id);
const locker = db.sequelize.query(`SELECT * FROM ems_device where locker_station_id="${locker_station_id}"`,{  plain: true,type: sequelize.QueryTypes.SELECT})
.then(locker => { // data is equal to the result of line 1.
// console.log(locker);
    if(locker){
        // console.log(locker);

        if(locker.status == 0){
            res.status(422).json(ResponseFormat.error(
            'locker_station_offline',
            reference_id,
            422
            ))
        }
        else if(locker.status == 2){
            res.status(422).json(ResponseFormat.error(
            'locker_station_retired',
            reference_id,
            422
            ))
        }
        getLockerboxCategory(req, res);
        const locker_box_category = req.locker_box_category;
        const drawer_resource_info = db.sequelize.query(`SELECT * FROM ems_drawer_resource_info  where device_number="${locker.device_number}" and drawer_status=0`,{ type: sequelize.QueryTypes.SELECT})
        .then(drawer_resource_info => { // data is equal to the result of line 1.
            if(drawer_resource_info.length == 0){
                res.status(422).json(ResponseFormat.error(
                'insufficient_capacity',
                reference_id,
                422
                ))
            }

        });
    }
});
}
function getLockerboxCategory(req, res){
// console.log(req.body.parcel_length);
const parcel_length = req.body.parcel_length || 0;
const parcel_height = req.body.parcel_height || 0;
const parcel_width  = req.body.parcel_width || 0;
const parcel_weight = req.body.parcel_weight || 0;

const small_box_length = 43;
const small_box_height = 8;
const small_box_width = 47;

const medium_box_length = 43;
const medium_box_height = 19;
const medium_box_width = 47;

const large_box_length = 43;
const large_box_height = 28;
const large_box_width = 47;

if(parcel_height < small_box_height && parcel_width < small_box_width && parcel_length < small_box_length){
    // small box
   req.locker_box_category = 3;
   req.locker_box_cost = 1;
}
else if(parcel_height < medium_box_height && parcel_width < medium_box_width && parcel_length < medium_box_length )
{
    //medium box
   req.locker_box_category = 2;
   req.locker_box_cost = 1.5;
}
else if(parcel_height < large_box_height && parcel_width < large_box_width && parcel_length < large_box_length )
{
    //large box
   req.locker_box_category = 1;
   req.ocker_box_cost = 2;
}else{
   res.status(422).json(ResponseFormat.error(
                'parcel_is_too_large',
                req.reference_id||'',
                422
                ));
    res.end();

}

最佳答案

欢迎来到 NodeJS 异步环境。使用时res.json响应将被写入并且流将结束,没有使用 res.end()当使用res.json时。 使用res.json当你拥有所需的一切时。

根据您的代码,您可以在locker.之后创建一个else分支。声明:

exports.createBooking = (req, res) => {
  // Save Order to Database
  console.log("Processing func -> Create Booking");
  // console.log(req.body);
  const business_code = 'Test' + new Date("03/25/2015") + Math.floor(Math.random() * 9999999999999) + 1;
  const locker_station_id = req.body.locker_station_id || '';
  const reference_id = req.body.reference_id || '';
  console.log(locker_station_id);
  const locker = db.sequelize.query(`SELECT * FROM ems_device where locker_station_id="${locker_station_id}"`, {
      plain: true,
      type: sequelize.QueryTypes.SELECT
    })
    .then(locker => { // data is equal to the result of line 1.
      // console.log(locker);
      if (locker) {
        // console.log(locker);

        if (locker.status == 0) {
          res.status(422).json(ResponseFormat.error(
            'locker_station_offline',
            reference_id,
            422
          ))
        } else if (locker.status == 2) {
          res.status(422).json(ResponseFormat.error(
            'locker_station_retired',
            reference_id,
            422
          ))
        } else {

          let lockerBoxStatus = getLockerboxCategory(req, res); // you need to know the status of this method, go and check getLockerboxCategory

          // the stream will output the JSON if you reach the else branch, but make no mistake, the javascript is not done, the following lines will be evaluated.
          if (lockerBoxStatus) { // if this is 0, then you will not get a write error, because getLockerboxCategory will close the stream.

            const locker_box_category = req.locker_box_category;
            const drawer_resource_info = db.sequelize.query(`SELECT * FROM ems_drawer_resource_info  where device_number="${locker.device_number}" and drawer_status=0`, {
                type: sequelize.QueryTypes.SELECT
              })
              .then(drawer_resource_info => { // data is equal to the result of line 1.
                if (drawer_resource_info.length == 0) {
                  res.status(422).json(ResponseFormat.error(
                    'insufficient_capacity',
                    reference_id,
                    422
                  ))
                }

              });

          }


        }

      }
    });
}

function getLockerboxCategory(req, res) {
  // console.log(req.body.parcel_length);
  let status = 1; // assuming 1 by default
  const parcel_length = req.body.parcel_length || 0;
  const parcel_height = req.body.parcel_height || 0;
  const parcel_width = req.body.parcel_width || 0;
  const parcel_weight = req.body.parcel_weight || 0;

  const small_box_length = 43;
  const small_box_height = 8;
  const small_box_width = 47;

  const medium_box_length = 43;
  const medium_box_height = 19;
  const medium_box_width = 47;

  const large_box_length = 43;
  const large_box_height = 28;
  const large_box_width = 47;

  if (parcel_height < small_box_height && parcel_width < small_box_width && parcel_length < small_box_length) {
    // small box
    req.locker_box_category = 3;
    req.locker_box_cost = 1;
  } else if (parcel_height < medium_box_height && parcel_width < medium_box_width && parcel_length < medium_box_length) {
    //medium box
    req.locker_box_category = 2;
    req.locker_box_cost = 1.5;
  } else if (parcel_height < large_box_height && parcel_width < large_box_width && parcel_length < large_box_length) {
    //large box
    req.locker_box_category = 1;
    req.ocker_box_cost = 2;
  } else {
    status = 0;
    res.status(422).json(ResponseFormat.error(
      'parcel_is_too_large',
      req.reference_id || '',
      422
    ));
    //res.end(); // you don't need this `.json` will output+end the stream

  }
  return status;
}

PS:确保您的所有陈述都包含在 res.json 中或res.end()您认为结束流是适当的,否则网络服务器将挂起。并阅读 next来自中间件的参数 app.use((req, res, next)=> next(); ) ,当您想跳到下一个中​​间件时,您可能需要它。

关于javascript - 如何处理nodejs中的大量条件匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56427111/

相关文章:

javascript - 使用react访问全局javascript变量

javascript - 使用 jQuery 交换 div 内容

php - 在 session 中存储 php 变量并调用分页链接

MySQL 选择与使用复选框选择的类别完全匹配的行

node.js - TypeError : BrowserWindow is not a constructor

node.js - 为什么TypeORM需要提供OneToMany的反面,而不需要提供ManyToOne的反面?

javascript - 在 JavaScript 中缩短成员方法中的对象名称

javascript - jQuery 每个错误 :Uncaught TypeError: Cannot use 'in' operator to search for '18' in div[data-role=page]

php - 通过JQuery ajax将多个数组传递到php文件

javascript - nodejs异步嵌套调用