Node.js什么都不返回?

时间:2016-08-27 17:58:03

标签: javascript node.js mean-stack

为什么usernametoid函数不会返回任何内容?我知道它通过安慰它存在,但它不会存储在otherplayerid变量中?为什么呢?

我的应用程序:(调用post api kill)

var userFunc   = require('../factory/user_factory.js');

    app.post('/api/kill', function (req, res) {

        var username = "signature";//req.query.username;

        var otherplayerid = userFunc.usernametoid(username);
 if (!(otherplayerid)) {
                console.log("other player is acually " + otherplayerid);
                result.push("denne brukeren finnes ikke! " + otherplayerid);

            } else {

}
});

和我的user_factory:

var articles = require('../controllers/articles.server.controller'),
    path = require('path'),
    mongoose = require('mongoose'),
    Article = mongoose.model('Article'),
    Users = mongoose.model('User'),
    errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));



exports.usernametoid = usernametoid;





    function usernametoid(id) {

        var query = Users.findOne( { username : id } );
        query.exec(function(err, datas) {
console.log(datas._id);
            return datas._id;
        });
    }

控制台:

 other player is acually undefined
    57c1c0f3b6b20c011242bf22

1 个答案:

答案 0 :(得分:1)

您需要了解异步调用。这是db请求。简单的修复就是回调:

function something(data, callback) {
    return callback('some data from db')
}

something('x', function(cb) {
    console.log(cb)
}

最好返回两个值(错误,回调)。但是你可以稍后阅读。 还有承诺。您可以阅读有关回调的内容,但建议您同时了解它们。