【问题标题】:javascript nodejs if statements being invoked in unexpected orderjavascript nodejs if语句以意外的顺序调用
【发布时间】:2017-06-17 17:05:19
【问题描述】:

鉴于下面的代码,我假设我遇到了异步问题。

exports.existingCheck = function (req, res, next) {

    var query = [],
        message = [],
        userObj = {},
        i, body = req.body;

    if(body.displayName){
        var regex = new RegExp(["^", body.displayName, "$"].join(""), "i");
    };

    if(req.user){
        var userObj = req.user;
    }

    if (body.displayName !== userObj.displayName) {
        console.log('body n no match')
        query.push({
            displayName: regex
        });
    }
    if (body.email !== userObj.email) {
        console.log('body e no match')

        query.push({
            email: body.email
        });
    }
    console.log('query pre ', query)

    if (query.length) {
        console.log('query init ', query)
        //find a match for email or display name and send appropriate error message;
        User.find({
                $or: query
            },
            function (err, existing) {
                if (err) {
                    console.log('register er ', err)
                }
                if (existing.length) {

                    for (i = 0; i < existing.length; i++) {

                        var conditional1 = false, conditional2 = false;

                        console.log('conditional1 init ', conditional1)

                        if(body.displayName && (userObj._id !== existing[i]._id)){
                            conditional1 = body.displayName.toLowerCase() === existing[i].displayName.toLowerCase();
                        };

                        console.log('conditional1 after ', conditional1)

                        if(body.email && (userObj._id !== existing[i]._id)){
                            conditional2 = body.email.toLowerCase() === existing[i].email.toLowerCase();
                        }

                        if (conditional2) {
                            message.push('Email is not unique.');
                        }

                        if (conditional1) {
                            message.push('Display name has already been taken.');
                        }
                    }
                }
            });
    }
    console.log('message check ', message)
    if (message.length) {
        return res.status(409).send({
            'message': message
        });
    }
    console.log('next')
    next();
};

下面的代码导致 console.logS 按此顺序触发:

body n no match
query pre  [ { displayName: /^bobohead$/i } ]
query init  [ { displayName: /^bobohead$/i } ]
message check  []
next
conditional1 init  false
conditional1 after  true

问题在于,直到调用消息检查和 next() 之后,条件才接收到它们的值。

我认为 if 语句是阻塞代码,一个会等待另一个被触发。

我假设我需要添加一个 else 语句来调用一个函数,该函数调用消息检查和 next() & 在初始 if 语句的末尾调用相同的函数。

我是否还需要确保在 else 语句中调用 next(),以确保在消息检查中的返回处理完成之前不会调用它? :

console.log('message check ', message)
if (message.length) {
    return res.status(409).send({
        'message': message
    });
}
else{
  console.log('next')
  next();
 }
};

【问题讨论】:

  • 究竟是什么问题?是不是console.log 总是记录{ displayName: /^bobohead$/i }
  • 不,在 next() 或消息/错误检查之前不调用条件。

标签: javascript node.js asynchronous async.js


【解决方案1】:

这看起来您对User.find 的调用是异步的;因此,您传递的回调函数中的代码会在包含的existingCheck 函数返回后执行。

如果您希望仅在 User.find 调用完成后发生某些事情,您也必须将该代码放入回调中。

请注意,您不能从回调内部的封闭函数返回值。毕竟,当回调执行时,封闭函数已经完成。如果要返回异步值,请改为返回 Promise(或将值传递给回调)。

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2023-03-25
    • 2020-03-08
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多