0

I am trying to add in the Node.js id to session retrieved from the database. I edits the steam-login for this purpose, but everything except the passing of the id works. I know why it does not work. This is because the query in node.js is asynchronous. Unfortunately, I do not know how to solve it, to return it in a function.

req.user = user;
connection.query("select * from users where steamid = "+user.steamid, function(err, row){
  if(err) {
    throw err;
  } else {
    req.user.id = row[0].id;
    //And now when i trying to console.log(req.user.id) i will se the id from database.
  }
});
    //But here when i try console.log(req.use.id) i see undefined.

I need to set req.user.id = id from database.
i can't do it like up, because this dont work.

XsiSecOfficial
  • 954
  • 8
  • 20

1 Answers1

0

As soon as your get the query result, return it:

user.find('first', { where: "steamid = " + player.steamid }, function(err, row) {
    if (row === undefined || row === null) {
        user.save();
    } else {
        user.set('id', row.id);
        user.save();
    }                                                              
});

user.find('first', { where: "steamid = " + player.steamid }, function(err, row) {
    return Promise.resolve({
        id: row.id,
        _json: player,
        steamid: steamID,
        username: player.personaname,
        name: player.realname,
        profile: player.profileurl,
        avatar: {
            small: player.avatar,
            medium: player.avatarmedium,
            large: player.avatarfull
        },
        hascsgo: hascsgo
     });                                                           
 });
Sebastian S
  • 807
  • 6
  • 15
  • Unfortunately, this does not work, then the rest of the code does not call and the user is not added to the session. –  Jan 15 '18 at 00:40
  • What result are your getting once you fetch your function ? – Sebastian S Jan 15 '18 at 01:18
  • I can see. It's undefined because is out of the scope. You'll have to put your logic beneath the else{} statement, where the id still exists – Sebastian S Jan 15 '18 at 03:25