如何让我的代码更清晰

时间:2022-03-20 13:37:13

The code is for handling the POST request within Expressjs and mongodb

该代码用于处理Expressjs和mongodb中的POST请求

router.post('/', function(req, res){
  var data = req.body;
  Tag.find({name: data.name}).limit(1).exec( function(err, result){
    if(err){
    } else {
      if(result.length > 0){ // Already exist a tag with same name
        res.status(400).end('Already exist!');
      } else { // Save the new Tag to database
        var tag = new Tag();
        tag.name = data.name;
        tag.lastModifier = req.user?req.user.username:"system";
        tag.lastModified = Date.now();
        tag.save(function(err){
          if(err){
            res.status(400).json({ 
              message: "insert tag error"
            });
          } else {
            Tag.findOne(tag, function(err, result){
              if(err){          
                res.status(400).json({
                  message: "some error.."
                });
              } else {
                //res.status(400).end('same tag name');
                res.status(201).json({
                  _id: result._id
                });          
              }
            });
          }
        });
      }
    }
  });
});

The stairs in the last 9 lines are terrible....please teach me how could I make this mess clearer?

最后9行的楼梯很糟糕....请教我如何让这个混乱更清楚?

4 个解决方案

#1


0  

I really recommend you to try promises. There are many implementations available for JavaScript and Node.js.

我真的建议你尝试承诺。有许多可用于JavaScript和Node.js的实现。

A promise basically encapsulates an asynchronous operation into a value, which allows you to get rid of these horrible nested callbacks. They also allow you to chain asynchronous operations more easily.

承诺基本上将异步操作封装到一个值中,这允许您摆脱这些可怕的嵌套回调。它们还允许您更轻松地链接异步操作。

What you're forced to do in your callback-based code is to check errors at every level, which can get rather tedious if your error handling could be at one place. Promises will propagate the error, allowing easy handling in one place.

您在基于回调的代码中*执行的操作是检查每个级别的错误,如果您的错误处理可能在一个地方,则会变得相当繁琐。 Promise会传播错误,允许在一个地方轻松处理。

Here are some references:

以下是一些参考:

It might take a little while to adjust to using them, but trust me, it is absolutely worth it.

调整使用它们可能需要一段时间,但请相信我,这绝对是值得的。

#2


1  

You can use named functions instead of some of the function expressions:

您可以使用命名函数而不是某些函数表达式:

router.post('/', function(req, res){
  var data = req.body;
  Tag.find({name: data.name}).limit(1).exec( function(err, result){
    if(err){
    } else {
      if(result.length > 0){ // Already exist a tag with same name
        res.status(400).end('Already exist!');
      } else { // Save the new Tag to database
        var tag = new Tag();
        tag.name = data.name;
        tag.lastModifier = req.user?req.user.username:"system";
        tag.lastModified = Date.now();
        tag.save(save(err));
      }
    }
  });
});

function save(err){
  if(err){
    res.status(400).json({ 
      message: "insert tag error"
    });
  } else {
    Tag.findOne(tag, handleResult(err, result));
  }
}

function handleResult(err, result){
  if(err){          
    res.status(400).json({
      message: "some error.."
    });
  } else {
    //res.status(400).end('same tag name');
    res.status(201).json({
      _id: result._id
    });          
  }
}

(You can surely name them a little more appropriate for the situation, but it shows the principle.)

(你可以肯定地将它们命名为更合适的情况,但它显示了原则。)

#3


1  

router.post('/', function(req, res){
  var data = req.body;
  Tag.find({name: data.name}).limit(1).exec(cbExec);
});


function cbExec(err, result){
    if(err){
    } else {
        if(result.length > 0){ // Already exist a tag with same name
            res.status(400).end('Already exist!');
        } else { // Save the new Tag to database
            var tag = new Tag();
            tag.name = data.name;
            tag.lastModifier = req.user?req.user.username:"system";
            tag.lastModified = Date.now();
            tag.save(cbSave);
        }
    }
}

function cbSave(err){
    if(err){
        res.status(400).json({message: "insert tag error"});
    } else {
        Tag.findOne(tag, cbTag);
    }
}

function cbTag(err, result){
    if(err){        
        res.status(400).json({message: "some error.."});
    } else {
        //res.status(400).end('same tag name');
        res.status(201).json({_id: result._id});          
    }
}

#4


0  

You can separate the cod a little bi more. Instead of creating lambda functions create normal ones. You can get rid of one pair of braces in 4th line if(err){ } else {

你可以将鳕鱼分开一点点。而不是创建lambda函数创建正常的函数。如果(错误){} else {你可以在第4行摆脱一对大括号

using if(!err)

#1


0  

I really recommend you to try promises. There are many implementations available for JavaScript and Node.js.

我真的建议你尝试承诺。有许多可用于JavaScript和Node.js的实现。

A promise basically encapsulates an asynchronous operation into a value, which allows you to get rid of these horrible nested callbacks. They also allow you to chain asynchronous operations more easily.

承诺基本上将异步操作封装到一个值中,这允许您摆脱这些可怕的嵌套回调。它们还允许您更轻松地链接异步操作。

What you're forced to do in your callback-based code is to check errors at every level, which can get rather tedious if your error handling could be at one place. Promises will propagate the error, allowing easy handling in one place.

您在基于回调的代码中*执行的操作是检查每个级别的错误,如果您的错误处理可能在一个地方,则会变得相当繁琐。 Promise会传播错误,允许在一个地方轻松处理。

Here are some references:

以下是一些参考:

It might take a little while to adjust to using them, but trust me, it is absolutely worth it.

调整使用它们可能需要一段时间,但请相信我,这绝对是值得的。

#2


1  

You can use named functions instead of some of the function expressions:

您可以使用命名函数而不是某些函数表达式:

router.post('/', function(req, res){
  var data = req.body;
  Tag.find({name: data.name}).limit(1).exec( function(err, result){
    if(err){
    } else {
      if(result.length > 0){ // Already exist a tag with same name
        res.status(400).end('Already exist!');
      } else { // Save the new Tag to database
        var tag = new Tag();
        tag.name = data.name;
        tag.lastModifier = req.user?req.user.username:"system";
        tag.lastModified = Date.now();
        tag.save(save(err));
      }
    }
  });
});

function save(err){
  if(err){
    res.status(400).json({ 
      message: "insert tag error"
    });
  } else {
    Tag.findOne(tag, handleResult(err, result));
  }
}

function handleResult(err, result){
  if(err){          
    res.status(400).json({
      message: "some error.."
    });
  } else {
    //res.status(400).end('same tag name');
    res.status(201).json({
      _id: result._id
    });          
  }
}

(You can surely name them a little more appropriate for the situation, but it shows the principle.)

(你可以肯定地将它们命名为更合适的情况,但它显示了原则。)

#3


1  

router.post('/', function(req, res){
  var data = req.body;
  Tag.find({name: data.name}).limit(1).exec(cbExec);
});


function cbExec(err, result){
    if(err){
    } else {
        if(result.length > 0){ // Already exist a tag with same name
            res.status(400).end('Already exist!');
        } else { // Save the new Tag to database
            var tag = new Tag();
            tag.name = data.name;
            tag.lastModifier = req.user?req.user.username:"system";
            tag.lastModified = Date.now();
            tag.save(cbSave);
        }
    }
}

function cbSave(err){
    if(err){
        res.status(400).json({message: "insert tag error"});
    } else {
        Tag.findOne(tag, cbTag);
    }
}

function cbTag(err, result){
    if(err){        
        res.status(400).json({message: "some error.."});
    } else {
        //res.status(400).end('same tag name');
        res.status(201).json({_id: result._id});          
    }
}

#4


0  

You can separate the cod a little bi more. Instead of creating lambda functions create normal ones. You can get rid of one pair of braces in 4th line if(err){ } else {

你可以将鳕鱼分开一点点。而不是创建lambda函数创建正常的函数。如果(错误){} else {你可以在第4行摆脱一对大括号

using if(!err)