【问题标题】:Wait for validation (serverside) to complete befor insert into database在插入数据库之前等待验证(服务器端)完成
【发布时间】:2016-01-24 13:56:17
【问题描述】:

对于服务器端的东西,我对 Node.js 或 Javascript 还是很陌生。目前我正在尝试验证一些用户输入并在出现问题时设置默认值。现在,如果我运行验证,则 json 对象会在我的验证完成之前出现在数据库中。

  1. 我目前进行验证的方式可能不是最好的,但如果有人可以解释我的行为,我很确定我将来可以更好地理解 Javascript。
  2. 是否有更好的方法通过回调、中间件进行验证(无需 mongoose 或其他 ODM 模块),或者我应该使用一些异步模块吗?

这是我的代码:

module.exports = function(app, express, todoDB, listDB, statusDB) {
var moment = require('moment');
var todoRouter = express.Router();
todoRouter.post('/', function(req, res, next) {
        console.log('1');
        if (!(moment(req.body.createDate).isValid())) {
            req.body.createDate = moment().format("DD-MM-YYYY HH:mm:ss");
        }
        else {
            req.body.createDate = moment(req.body.createDate).format("DD-MM-YYYY HH:mm:ss");
        }
        console.log('2');
        if (req.body.list_id == '') {
            listDB.findOne({list: 'Neu'}, function(reqdb, docs) {
                if (docs == null) {
                    listDB.insert({list: 'Neu', index: 1});
                    listDB.findOne({list: 'Neu'}, function(reqdb, docs) {
                        console.log('AnlageListID');
                        console.log(docs._id);
                        req.body.list_id = docs._id;
                    });
                }
                else {
                    console.log('BestehendeListID');
                    console.log(docs._id);
                    req.body.list_id = docs._id;
                }
            });
        }
        console.log('3');
        if (req.body.status_id == '') {
            statusDB.findOne({status: 'offen'}, function(reqdb, docs) {
                if (docs == null) {
                    statusDB.insert({status: 'offen', index: 1});
                    statusDB.findOne({status: 'offen'}, function(reqdb, docs) {
                        console.log('AnlageStatusID');
                        console.log(docs._id);
                        req.body.status_id = docs._id;
                    });
                }
                else {
                    console.log('BestehendeStatusID');
                    console.log(docs._id)
                    req.body.status_id = docs._id;
                }
            });
        }
        console.log('4');
        console.log('StatusID');
        console.log(req.body.status_id);
        console.log('ListID');
        console.log(req.body.list_id);
        todoDB.insert({
            todo: req.body.todo,
            createDate: req.body.createDate,
            endDate: req.body.endDate,
            discription: req.body.discription,
            comment: req.body.comment,
            list_id: req.body.list_id,
            priority_id: req.body.priority_id,
            section_id: req.body.section_id,
            user_id: req.body.user_id,
            status_id: req.body.status_id,
            company_id: req.body.company_id
        });
        res.json({message: 'TODO erfolgreich hinzugefügt!'});
    });
    return todoRouter;
};

...这是输出:

1
2
3
4
StatusID

ListID

POST /api/todos 200 76.136 ms - 44
BestehendeListID
M3Xh46VjVjaTFoCM
BestehendeStatusID
48v80B4fbO87c8um

PS:它是一个小“项目”,只是为了我学习 MEAN Stack,所以我正在使用 neDB。

【问题讨论】:

    标签: node.js validation asynchronous express


    【解决方案1】:

    如果我理解正确,您尝试顺序执行多个异步调用并在代码中引入检查以验证先前的异步调用是否已完成。这在一般情况下不起作用,因为您的检查可能会在异步调用通过之前进行处理。它可能偶尔会起作用,但我什至不会期望。

    为此有标准机制。其中一个使用 Promise,另一个使用 async,如果将所有回调堆叠在一起,还有另一个使用。下面我将演示如何使用async 来解决这个问题,但同样的一般想法也适用于使用 Promise。检查 Github 上的 async 项目,以下部分解决方案将变得清晰:

    var async = require("async")
    async.waterfall([
        function(next) {
            listDB.findOne({list: 'Neu'}, next); // quits on error
        },
        function(doc, next) {
            if (doc) {
                return next(null, doc._id);
            } 
            statusDB.insert({status: 'offen', index: 1}, function(err) {
                if (err) return next(err); // quit on error
                statusDB.findOne({status: 'offen'}, function(err, doc) {
                        next(err, doc._id); // quits on error
                });
            });
        },
        function(id, next) {
            // do next step and so on
            next();
        }
    ], 
    // this is the exit function: it will get called whenever an error 
    // is passed to any of the `next` callbacks or when the last 
    // function in the waterfall series calls its `next` callback (with
    // or without an error)
    function(err) {
        console.error("Error processing:", err)
    });
    

    【讨论】:

    • 我们可以停止使用和推送async 模块吗?承诺现在是一回事。
    • 我们不能。这是一个完全有效的选择。正如我所说,有一些解决方案,promise 就是其中之一。
    • 你说得对。我来自 java 背景,所以在理解异步调用/回调时遇到了一些问题。你能给我一个在这种情况下堆叠回调的例子吗,即使它不是最佳实践?
    • @Stefan 这真的是我不想经历的选项。真的,坚持承诺或async。承诺将是你在dartC# 中也有的东西,并且可能是长期的方式,但恕我直言async 如果所有这些对你来说都是新的,那么更容易理解。
    • 好的,我将锁定 Promise 和异步。不过还是非常感谢。如果我想了解异步调用和回调的概念,我必须了解更多关于 javascript 的知识,对吗?如果您有任何进一步的信息我应该从哪里开始,我将不胜感激。
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2014-07-23
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多