首页 > 解决方案 > 有没有办法重构和简化这个服务器端代码?

问题描述

下面的代码是我的应用程序中的中间件之一,它的作用是当用户向服务器发送 post 请求时,它将表单数据保存到引擎表,然后加载所有相关引擎数据以提取平均值以插入新的数据到火箭表中相应的火箭。虽然它有效,但显然我的代码是如此不必要的嵌套(我认为)和冗长,因为我不熟悉承诺..

  1. 我怎样才能写出更好的代码或者至少简化一点呢?
  2. 我从代码中不明白的一件事是在注释行中。
  3. 谢谢你。

const express = require('express');
const app = express();
const logger = require('morgan');
const knex = require('./db/index.js');
const bodyParser = require('body-parser');
const { check, validationResult, body } = require('express-validator/check')
app.use(logger(':method :url :status :date[clf]'));
app.use(express.static("public"));
app.use(bodyParser.json());



app.post('/engines/:id', (req, res) => {
    knex('engines').insert({ 
        rocket_id: req.params.id,
        user_id: 1,
        price: req.body.price,
        shining: req.body.shining,
        texture: req.body.texture,
        modern: req.body.modern,
        hardness: req.body.hardness,
        loud: req.body.loud,
        power: req.body.power,
        explosion_risk: req.body.explosion_risk
    }).then( () => {
        const rocket_temp = {};
        return rocket_temp;
    }).then( rocket_temp => {
        const knexWhere = knex('engines').where({rocket_id: req.params.id});

        knexWhere.first().count('explosion_risk').then( data => {
            rocket_temp.total_count_risk = data.count;
            return rocket_temp;
        }).then( rocket_temp => {
            knexWhere.where({explosion_risk: true}).first().count('explosion_risk').then( data => {
                rocket_temp.countTrue = data.count;
                return rocket_temp;
            }).then( rocket_temp => {
                const knexWhere = knex('engines').where({rocket_id: req.params.id}); // I don't get why knexWhere variable must be re-assigned at this point. Otherwise it won't know that it should load data from 'evaluations' table. Simply saying, the value assigned to knexWhere variable is suddenly changed from this point.(Somehow it loads data from rockets table).

                knexWhere.first(knex.raw('ROUND(AVG(price))')).then( data => {
                    rocket_temp.avg_price = data.round;
                    return rocket_temp;
                }).then( rocket_temp => {
                    knexWhere.first(knex.raw('ROUND(AVG(shining))')).then( data => {
                        rocket_temp.avg_shining = data.round;
                        return rocket_temp;
                    }).then( rocket_temp => {
                        knexWhere.first(knex.raw('ROUND(AVG(texture))')).then( data => {
                            rocket_temp.avg_texture = data.round;
                            return rocket_temp;
                        }).then( rocket_temp => {
                            knexWhere.first(knex.raw('ROUND(AVG(modern))')).then( data => {
                                rocket_temp.avg_modern = data.round;
                                return rocket_temp;
                            }).then( rocket_temp => {
                                knexWhere.first(knex.raw('ROUND(AVG(hardness))')).then( data => {
                                    rocket_temp.avg_hardness = data.round;
                                    return rocket_temp;    
                                }).then( rocket_temp => {
                                    knexWhere.first(knex.raw('ROUND(AVG(loud))')).then( data => {
                                        rocket_temp.avg_loud = data.round;
                                        return rocket_temp;    
                                    }).then( rocket_temp => {
                                        knexWhere.first(knex.raw('ROUND(AVG(power))')).then( data => {
                                            rocket_temp.avg_power = data.round;
                                            return rocket_temp;
                                        }).then( rocket_temp => {
                                            
                                            knex('rockets').where({id: req.params.id}).first().update({
                                                price: rocket_temp.avg_price,
                                                shining: rocket_temp.avg_shining,
                                                texture: rocket_temp.avg_texture,
                                                modern: rocket_temp.avg_modern,
                                                hardness: rocket_temp.avg_hardness,
                                                loud: rocket_temp.avg_loud,
                                                power: rocket_temp.avg_power,
                                                explosion_risk: Math.round(parseInt(rocket_temp.countTrue)/parseInt(rocket_temp.total_count_risk) * 100)
                                            }).then( res => {
                                                knex('rockets').select().then( res => console.log(res) )
                                            })
                                        })
                                    })
                                })
                            })
                        })
                    })
                })
            })
        })                            
    }).then( result => res.sendStatus(201) );
})

   

标签: javascriptnode.jsexpresspromiseknex.js

解决方案


推荐阅读