【问题标题】:How to return nested function value in Nodejs [duplicate]如何在Nodejs中返回嵌套函数值[重复]
【发布时间】:2015-09-11 06:25:27
【问题描述】:

我被困在从用于验证用户的函数中获取结果返回中。

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))

谁能给我一些关于如何修复它的提示?

非常感谢

【问题讨论】:

  • 异步,异步,异步。您的 connection.query() 函数是异步的。这意味着它会在稍后的某个时间调用它的回调,在isAspAuth() 已经返回很久之后。您不能从这样的函数返回异步值。相反,您必须将回调传递给isAspAuth(),并在您获得最终值并且只能使用该回调中的值时调用该回调。这类问题有数百个重复。我会去找一个来标记的。

标签: mysql node.js


【解决方案1】:

问题是:

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

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

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

只有在查询完成后你的回调函数才会被执行,这不会连续发生。默认情况下它是异步的。这就是为什么你得到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();

【讨论】:

  • 请不要发布有很多很多重复问题的答案。相反,只需投票关闭作为重复项。如果有很多重复的人都在问同一个问题,这只会污染 StackOverflow 世界。
  • @jfriend00 - 是的,从现在开始,请记住这一点。顺便说一句,感谢您的指点。
猜你喜欢
  • 2014-09-01
  • 2015-04-19
  • 2020-05-11
  • 2021-04-15
  • 1970-01-01
  • 2015-08-01
  • 2011-03-23
  • 2015-07-20
相关资源
最近更新 更多