Nodejs:等待承诺得到解决

时间:2017-12-06 10:54:08

标签: javascript node.js

在此代码中,变量adminName和adminPassword应在执行if语句之前获取值。但是如果语句在then处理函数之前执行。这就是为什么验证不起作用。

function validateAdminLogin()
{

var adminName="";
var adminPassword="";   

var isValid=true;

var UserDAO = require('./js/DAO/UserDAO');  
var wait=require('wait.for-es6');
var admin=document.getElementById("adminform").elements.namedItem("username").value;
var adminPwd=document.getElementById("adminform").elements.namedItem("pwd").value;




    UserDAO.getAdminCredentials().then(function(rows){

    adminName= rows.username;
    adminPassword=rows.password;

    alert(admin+"----"+adminName);

    },function(error){
    alert(error);
    console.log(error);
    });



    //alert(admin+"-------"+adminName);

if(admin!==adminName) 
{
alert("Invalid username");
isValid=false;
}


if(adminPwd!==adminPassword) 
{
alert("Invalid password");
isValid=false;
} 

return isValid;
}

我还包括我已写下承诺的代码。

getAdminCredentials: function()
{
    var deferred = q.defer(); 

    $query =  "SELECT * FROM `user` where type='administrator' ";

    connection.connect(function(err) {

        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }

     // console.log("Successfully connected.");
    });

    connection.query($query, function(err, rows, fields) {
        if(err){
            console.log("An error ocurred performing the query.");
            console.log(err);
            deferred.reject(err);
            return;
        }
        else
            {
             console.log("Query succesfully executed");
            userDTO.setUserId(rows[0].user_id);
           userDTO.setUsername(rows[0].username);
           userDTO.setPassword(rows[0].password);

           deferred.resolve(userDTO);

            }



    }); 


    return deferred.promise;

    connection.end();
}

我如何处理nodejs的这种异步性质?请帮忙。

2 个答案:

答案 0 :(得分:0)

您只需将if语句放在then()语句中。

需要凭据的所有内容都应该放在then或者then()之后。 例如,您可以回复您的承诺:

return UserDAO.getAdminCredentials().then(function(rows){ ...

并在调用函数时向其添加then():

validateAdminLogin().then( ... )

答案 1 :(得分:0)

您可以像这样重写validateAdminLogin函数:

function validateAdminLogin() {
    var UserDAO = require('./js/DAO/UserDAO');
    var wait = require('wait.for-es6');
    var admin = document.getElementById("adminform").elements.namedItem("username").value;
    var adminPwd = document.getElementById("adminform").elements.namedItem("pwd").value;

    // return a promise which will be resolved with a bool indicating the "valid" status
    // the promise can reject when there was an error
    return UserDAO.getAdminCredentials().then(function(rows) {
        var adminName = rows.username;
        var adminPassword = rows.password;

       if (admin !== adminName) {
           alert("Invalid username");
           return false
       }

       if (adminPwd !== adminPassword) {
           alert("Invalid password");
           return false
       }

       return true
   }, function(error) {
       console.log(error);
   });
}

你必须处理你的函数调用有些不同,因为它不会立即返回bool。您的呼叫网站将如下所示:

validateAdminLogin().then(function (isValid) {
    // handle the "isValid" bool
}, function (error) {
    // handle the error...
});

不能同步node.js中的异步操作。