0

why wont usernametoid function return anything? i know it exist by consoling it out, but it wont store in the otherplayerid variable? why?

my app: ( calling 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 {

}
});

and my 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;
        });
    }

console:

 other player is acually undefined
    57c1c0f3b6b20c011242bf22
Hello
  • 77
  • 1
  • 13
maria
  • 207
  • 5
  • 22
  • 56

1 Answers1

1

You need to read about asynchronous calls. Which is db request. Simple fix is callback:

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

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

it is good practise to return two values (error, callback). But you can read it later on. There are also promises. You can read about them insted of callbacks, but it is recommended to know both.

kWeglinski
  • 411
  • 4
  • 14
  • 1
    We should generally try to avoid answering questions for which there are hundreds of duplicates of the same basic question as it just pollutes the stackoverflow search. This is one of those cases. – jfriend00 Aug 27 '16 at 18:08
  • @jfriend00 understood sir. I'll keep that in mind next time. – kWeglinski Aug 27 '16 at 18:11
  • I do have a question @jfriend00 regarding async – maria Aug 27 '16 at 18:12
  • @maria - If you've thoroughly studied the answer yours was marked a duplicate of and if it's quick and short, you can put it in a comment here addressed to me (under your question, not under this answer). If it's not quick and short and if you've searched and you don't think your question is already answered in other answers here on stackoverflow, then you can post a new question. – jfriend00 Aug 27 '16 at 18:18