如何简化此代码

时间:2017-12-17 12:06:17

标签: node.js mongodb express mongoose

在这里,我正在尝试创建一列新列车,并在接下来的5天内为该列车添加座位可用信息。我在这里重复做事。我想知道如何简化这段代码。

这里我使用express,mongoose和moment.js来生成日期。

app.post("/admin",[
hasAccess('admin'),
function(req,res,next){
    var today = moment();
                 Train.create(req.body.train,function(err,train){
                     if(err){
                         console.log(err);
                     }else{
                           Availability.create({date:moment(today).add(0, 'days').format("DD-MM-YYYY"),available:10},function(err,avail){
                               if(err){
                                   console.log(err);
                               }else{
                                   train.availabilities.push(avail);
                                   Availability.create({date:moment(today).add(1, 'days').format("DD-MM-YYYY"),available:10},function(err,avail){
                                       if(err){
                                           console.log(err);
                                       }else{
                                           train.availabilities.push(avail);
                                           Availability.create({date:moment(today).add(2, 'days').format("DD-MM-YYYY"),available:10},function(err,avail){
                                               if(err){
                                                   console.log(err);
                                               }else{
                                                   train.availabilities.push(avail);
                                                   Availability.create({date:moment(today).add(3, 'days').format("DD-MM-YYYY"),available:10},function(err,avail){
                                                       if(err){
                                                           console.log(err);
                                                       }else{
                                                           train.availabilities.push(avail);
                                                           Availability.create({date:moment(today).add(4, 'days').format("DD-MM-YYYY"),available:10},function(err,avail){
                                                               if(err){
                                                                   console.log(err);
                                                               }else{
                                                                   train.availabilities.push(avail);
                                                                   train.save(); 
                                                                   res.redirect("/trains/"+train._id);
                                                               }
                                                           })

                                                       }
                                                   })

                                               }
                                           })

                                       }
                                   })

                               }
                           })
                     }

                 });


}
]);

2 个答案:

答案 0 :(得分:1)

  

1 - 使用承诺

 app.post("/admin", [
    hasAccess('admin'),
    function (req, res, next) {
        var today = moment();
        const days = [0, 1, 2, 3, 4];
        let createdTrain;
        Train.create(req.body.train)
            .then(train => {
                createdTrain = train;
                return Promise.all(days.map(day => {
                    return Availability.create({
                        date: moment(today).add(day, 'days').format("DD-MM-YYYY"),
                        available: 10
                    });
                }));
            })
            .then(result => {
                createdTrain.availabilities = result;
                createdTrain.save();
            })
            .then(saved => {
                res.redirect("/trains/" + saved._id);
            })
            .catch(err => {
                console.log(err);
            });
    }
]);
  

2 - 使用async等待[node 7.6 +]

 app.post("/admin", [
  hasAccess("admin"),
  async (req, res, next) => {
    try {
      const today = moment();
      const DAYS = [0, 1, 2, 3, 4];
      const train = await Train.create(req.body.train);
      const result = await Promise.all(
        DAYS.map(day => {
          return Availability.create({
            date: moment(today)
              .add(day, "days")
              .format("DD-MM-YYYY"),
            available: 10
          });
        })
      );
      train.availabilities = result;
      const saved = await train.save();
      res.redirect("/trains/" + saved._id);
    } catch (err) {
      console.log(err);
    }
  }
]);

答案 1 :(得分:0)

您还可以使用 async 包通过 async.parallel 并行创建可用性对象,这样可以快速执行并创建一个可以创建可用性对象的函数。

app.post("/admin", [
    hasAccess('admin'),
    function (req, res, next) {
        var today = moment();
        Train.create(req.body.train, function (err, train) {
            if (err) {
                console.log(err);
            } else {
                var functionArr = [];
                for (var i = 0; i < 5; i++) {
                    var availFunction = function (i, callback) {
                        availability(moment(today), 0, 10, function (err, avail) {
                            if (err) {
                                return callback(err);
                            }
                            return callback(null, avail);
                        });
                    }
                    functionArr.push(availFunction);
                }
                async.parallel([
                    functionArr
                ], function (err, results) {
                    if (err) {
                        console.log(err);
                    }
                    train.availabilities.push(results);
                    train.save();
                    res.redirect("/trains/" + train._id);
                });
            }
        });
    }
]);

function availability(date, days, seats, callback) {
    Availability.create({
        date: moment(date).add(days, 'days').format("DD-MM-YYYY"),
        available: seats
    }, function (err, avail) {
        if (err) {
            return callback(err);
        } else {
            return callback(null, avail);
        }
    });
}