2016-07-28 86 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將永遠不會被調用,並且邏輯會被卡住。