如何将Express / Node.js代码从回调地狱转换为Promise

时间:2018-10-12 11:41:33

标签: javascript mysql node.js express promise

请。帮我。我真的很需要我只有8个小时才能重写2500行代码,否则我的科目会失败。

我使用express,mysql,nodejs

这是我的示例代码,我从数据库中放入了新产品。

这是我简单的“回调地狱”代码:

router.post('/inventory/product/add', authenticationMiddleware(), function(req, res, next) {
// Validate data
    req.assert('productslug', 'Product Slug is required').notEmpty()
    req.assert('productcat', 'Product Category is required').notEmpty()
    req.assert('productorigin', 'Product Inspiration is required').notEmpty()
    req.assert('productname', 'Product Name is required').notEmpty()
    req.assert('productprice', 'Product Price is required').notEmpty()
    req.assert('productdesc', 'Product Description is required').notEmpty()

    var errors = req.validationErrors()

    // No errors were found. Passed Validation!
    if (!errors) {

       var product = {
        productslug: req.sanitize('productslug').escape().trim(),
        productcat: req.sanitize('productcat').escape().trim(),
        productorigin: req.sanitize('productorigin').escape().trim(),
        productname: req.sanitize('productname').escape().trim(),
        productprice: req.sanitize('productprice').escape().trim(),
        productdesc: req.sanitize('productdesc').escape().trim()
    }

    const db = require('../db.js')
    let sql = `INSERT INTO inventory_tbl(product_slug, product_category, product_origin, product_name, product_price, product_cog, product_desc, total_stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`

    db.query(sql, [product.productslug, product.productcat, product.productorigin, product.productname, product.productprice, 0, product.productdesc, 0], (error, results, fields) => {
        if (error) {
            req.flash('error', error)

            // render to views/inventory/product/add.ejs
            res.render('admin/inventory/product/add', {
                title: 'Perry in Disguise | Add Product',
                productslug: product.productslug,
                productcat: product.productcat,
                productorigin: product.productorigin,
                productname: product.productname,
                productprice: product.productprice,
                productdesc: product.productdesc
            })
        } else {
            req.flash('success', 'Data added successfully!')

            res.render('admin/inventory/product/add', {
                title: 'Perry in Disguise | Add Product',
                productslug: product.productslug,
                productcat: product.productcat,
                productorigin: product.productorigin,
                productname: product.productname,
                productprice: product.productprice,
                productdesc: product.productdesc
            })
        }
    })
} else {
    // Display errors to the user
    var error_msg = ''
    errors.forEach(function(error) {
        error_msg += error.msg + '<br>'
    })
    req.flash('error', error_msg)

    // Using req.body.name
    // because req.param('name') is depreciated
    res.render('admin/inventory/product/add', {
        title: 'Perry in Disguise | Add Product',
        productslug: req.body.productslug,
        productcat: req.body.productcat,
        productorigin: req.body.productorigin,
        productname: req.body.productname,
        productprice: req.body.productprice,
        productdesc: req.body.productdesc
    })
   }
})

这是我用来添加产品的代码。我需要将其转换为Promise代码。真是难以理解的承诺。我搜寻并寻找参考,这是我认为最简单的例子。有人可以帮助我将我的代码转换为这种代码吗?这是链接:

https://jeremysu0131.github.io/Node-js-MySQL-with-Promise-%E8%A8%AD%E5%AE%9A/

1 个答案:

答案 0 :(得分:0)

首先,您需要使用Promise类并将一个函数传递给它,该函数获得两个参数,第一个是resolve中的参数,第二个是reject。在函数主体中,我们运行callback-based函数,并在回调中检查是否有错误,我们调用reject函数并传递error,如果没有错误,我们调用resolve并传递结果。 因此我们创建了一个Promise,现在我们需要使用它。为此,我们在.then变量上调用insertresult成功,在错误处调用.catch

router.post('/inventory/product/add', authenticationMiddleware(), function(req, res, next) {
// Validate data
    req.assert('productslug', 'Product Slug is required').notEmpty()
    req.assert('productcat', 'Product Category is required').notEmpty()
    req.assert('productorigin', 'Product Inspiration is required').notEmpty()
    req.assert('productname', 'Product Name is required').notEmpty()
    req.assert('productprice', 'Product Price is required').notEmpty()
    req.assert('productdesc', 'Product Description is required').notEmpty()

    var errors = req.validationErrors()

    // No errors were found. Passed Validation!
    if (!errors) {

       var product = {
        productslug: req.sanitize('productslug').escape().trim(),
        productcat: req.sanitize('productcat').escape().trim(),
        productorigin: req.sanitize('productorigin').escape().trim(),
        productname: req.sanitize('productname').escape().trim(),
        productprice: req.sanitize('productprice').escape().trim(),
        productdesc: req.sanitize('productdesc').escape().trim()
    }

    const db = require('../db.js')
    let sql = `INSERT INTO inventory_tbl(product_slug, product_category, product_origin, product_name, product_price, product_cog, product_desc, total_stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`
    const insertResult = new Promise((resolve, reject) => {
        db.query(sql, [product.productslug, product.productcat, product.productorigin, product.productname, product.productprice, 0, product.productdesc, 0], (error, results, fields) => {
            if (error) reject(error)
            else resolve(results)
        }
    });
    insertResult.then(result => {
            req.flash('success', 'Data added successfully!')

            res.render('admin/inventory/product/add', {
                title: 'Perry in Disguise | Add Product',
                productslug: product.productslug,
                productcat: product.productcat,
                productorigin: product.productorigin,
                productname: product.productname,
                productprice: product.productprice,
                productdesc: product.productdesc
            })
    }).catch(error => {
            req.flash('error', error)

            // render to views/inventory/product/add.ejs
            res.render('admin/inventory/product/add', {
                title: 'Perry in Disguise | Add Product',
                productslug: product.productslug,
                productcat: product.productcat,
                productorigin: product.productorigin,
                productname: product.productname,
                productprice: product.productprice,
                productdesc: product.productdesc
            })
    });
} else {
    // Display errors to the user
    var error_msg = ''
    errors.forEach(function(error) {
        error_msg += error.msg + '<br>'
    })
    req.flash('error', error_msg)

    // Using req.body.name
    // because req.param('name') is depreciated
    res.render('admin/inventory/product/add', {
        title: 'Perry in Disguise | Add Product',
        productslug: req.body.productslug,
        productcat: req.body.productcat,
        productorigin: req.body.productorigin,
        productname: req.body.productname,
        productprice: req.body.productprice,
        productdesc: req.body.productdesc
    })
   }
})