2016-07-28 83 views
0

我正试图发布到一个/用户/创建路径数据从一个表单,所有通过罚款,然后让它逐一检查数据是有效的,在某些情况下,在数据库中是唯一的。这是我用来检查登记表上输入的用户和电子邮件地址。承诺不等待之前的陈述完成。

该函数似乎正确查询,但最终,我收集的错误消息的console.log仅收集第一个条目。

// Check if variable is already is available or not 
var existsInDatabase = function(field, value){ 

    var deferred = Q.defer(); 
    var query = {}; 
    var errorMessage = {}; 

    query[field] = value; 

    User.find(query, function(err, docs){ 
    // If it finds it, then set a message for already existing 
    if(docs){ 
     errorMessage = {'type': 'alert', 'body': value + ' already exists in the database.'} 
     deferred.resolve(errorMessage); 
    } else { 
     deferred.reject(value + ' was not found in the database'); 
    } 

    }); 
    return deferred.promise; 
}; 

这里是我检查密码,看看它们是否匹配。

var doPasswordsMatch = function(password, confirmed){ 
    var deferred = Q.defer(); 

    console.log('Values passed into doPasswordsMatch() function:', password + ' ' + confirmed); 

    if(password !== confirmed){ 
    errorMessage = {'type': 'alert', 'body': 'The two passwords you entered do not match'}; 
    deferred.resolve(errorMessage); 
    }; 

    return deferred.promise; 
} 

这是我的路线与.then链接。

router.post('/user/create', function(req, res){ 

    var errorMessages = []; 

    existsInDatabase('userName', req.body.username) 
    .then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } }) 
    .then(existsInDatabase('userEmail', req.body.email)) 
    .then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } }) 
    .then(doPasswordsMatch(req.body.password, req.body.confirmedPassword)) 
    .then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } }) 
    .then(function(){ console.log(errorMessages); }); 

}); 

我猜我在哪里挣扎的。那么,如何防止一些东西触发,除非一切都完成之前的链接。

+0

为什么你有时会传递函数,有时会承诺'then'?你会期望'.then(console.log(errorMessages))'工作吗? – Bergi

回答

1

then()以函数作为参数(full specification),但是您传递第2个和第4个.then()的承诺。它应该工作,如果你把它们包装在匿名函数中。

... 
.then(function() { return existsInDatabase('userEmail', req.body.email); }) 
... 
.then(function() { return doPasswordsMatch(req.body.password, req.body.confirmedPassword); }) 
... 

return是如此的existsInDatabase()doPasswordsMatch()返回的承诺,决心在移动到下一个then()

但是之前,你可能需要重新考虑你的逻辑是成立的方式。就目前而言,如果密码确实匹配,那么下一个.then将永远不会被调用,并且逻辑会被卡住。