【问题标题】:Passing row.id from the database to return in the function - Node.js从数据库中传递 row.id 以在函数中返回 - Node.js
【发布时间】:2018-01-14 22:39:38
【问题描述】:

我正在尝试将 Node.js id 添加到从数据库检索到的会话中。 我为此目的编辑了蒸汽登录,但除了传递 id 之外的所有内容都有效。我知道为什么它不起作用。这是因为 node.js 中的查询是异步的。不幸的是,我不知道如何解决它,在函数中返回它。

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.

我需要从数据库中设置req.user.id = id
我做不到,因为这行不通。

【问题讨论】:

    标签: mysql node.js variables steam-web-api


    【解决方案1】:

    得到查询结果后立即返回:

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

    【讨论】:

    • 不幸的是,这不起作用,然后其余代码没有调用并且用户没有添加到会话中。
    • 获取函数后会得到什么结果?
    • 我可以看到。它是未定义的,因为它超出了范围。您必须将您的逻辑放在 else{} 语句下方,其中 id 仍然存在
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多