如何在Nodejs中返回嵌套函数值

时间:2015-09-10 22:02:39

标签: mysql node.js

我无法从用户身份验证函数中获取结果返回。

utility.isAspAuth = function(token){
    queryString = {
        sql: 'SELECT * FROM SecurityToken WHERE Token = ?',
        timeout: 40000, // 40s
        values: [token]
    };
    var curTime = new Date();
    connection.query(queryString,function(err,rows,field){
        if(err){
            console.log('error on query' + err);
        }else{

            var result = rows[0];

            result.forEach(function(element, index, array){
                if(Date.parse(result.Expires) > curTime){
                    return true;
                }else{
                    return false;
                }
            });
        }
    });
};

所以我在另一个文件中调用此函数,但结果是未定义的

console.log(utility.isAspAuth(token))

有人可以给我一些关于如何解决它的提示吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

问题是:

当您从另一个文件中调用utility.isAspAuth(token)时,utility文件中的函数正在执行但在通话时没有返回任何内容。

这是nodejs的本质。请注意您的代码 -

connection.query(queryString,function(err,rows,field){

只有在查询完成后才能执行上面一行中的回调函数,这不会连续发生。它默认是asyn。这就是为什么你得到nothing即。 undefined中的console.log()

修复:

使用承诺 -

https://github.com/kriskowal/q

  
    

如果某个函数无法返回值或者在没有阻塞的情况下抛出异常,则可以返回一个promise。“

  

在您的实用程序文件中 -

utility.isAspAuth = function(token){

    var deferred = Q.defer();
    /* require('q') in your nodejs code.
       You see at the last line of this function we return a promise object.
       And in your success / fail function we either resolve/ reject the promise. 
       Simple. See the usage in other file where you log.
    */

    queryString = {
        sql: 'SELECT * FROM SecurityToken WHERE Token = ?',
        timeout: 40000, // 40s
        values: [token]
    };
    var curTime = new Date();
    connection.query(queryString,function(err,rows,field){
        if(err){
            // console.log('error on query' + err);

            deferred.reject(new Error(err));

        } else {

            var result = rows[0];

            result.forEach(function(element, index, array){
                if(Date.parse(result.Expires) > curTime){

                    deferred.resolve(true);

                }else{

                    deferred.resolve(false);
                }
            });
        }
    });


     return deferred.promise;

};

在您的其他档案中

utility.isAspAuth(token)
.then(function (yourBoolResponse) {

    console.log(yourBoolResponse);
})
.catch(function (err) {

    // Handle error thrown here..
})
.done();