javascript nodejs if语句是否以意外顺序调用

时间:2017-02-01 03:41:44

标签: javascript node.js asynchronous async.js

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

 app_id  field_id  foo 
 ------  --------  -----
 1       sam       sam
 0       sam       NULL
 1       sam       sam
 2       bob       NULL
 NULL    bugs      NULL

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

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();
};

问题是条件在消息检查和next()被调用之前没有接收到它们的值。

我认为if语句是阻塞代码,而且会等待另一个被解雇。

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

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

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

1 个答案:

答案 0 :(得分:1)

这似乎是对User.find的调用是异步的;因此,传递的回调函数内的代码在包含existingCheck函数返回后执行。

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

请注意,您无法从回调内部返回封闭函数中的值。毕竟,在回调执行时,封闭功能已经完成。如果要返回异步值,请向其返回Promise(或将值传递给回调)。