无法使用节点/表达式从MySQL数据库返回

时间:2018-10-18 14:55:45

标签: javascript mysql node.js express

尝试重构节点/表达式中的某些代码。现在,在每条路线中,我都将访问数据库,并且如果发现重定向或渲染的内容。但是我重新输入了代码,例如selectUserById。

这是我的代码

  router.get("/users/:id", (req, res) => { 
    const userId = req.params.id;
    const newLocal = "SELECT * FROM Users WHERE id = ?";
    getConnection().query(newLocal, [userId] ,(err, rows, fields) => {
        if (err) {
            console.log(err);
            res.sendStatus(500);
        } else {             
            const user = rows.map((row) => {
                return {name: row.name, id: row.id}
            });
                res.render("users/showUser.ejs", {user: user});
        }      
    });
});

我想将其重构为类似的内容,如果selectUserById返回空内容,则执行某些操作,否则执行其他操作。问题是这段代码什么也没给我回报,console.log(users)给了我undefined

  router.get("/users/:id", (req, res) => {    
    const userId = req.params.id;
    const newLocal = "SELECT * FROM Users WHERE id = ?";
    const users = selectUserById(newLocal, userId, res);

    console.log(users);

    // if users==[]
       //user not found
    //else
       //res.render("users/showUser.ejs", {user: user});
});

function selectUserById(newLocal, userId, res) {
    var user;
    getConnection().query(newLocal, [userId], (err, rows, fields) => {
        if (err) {
            console.log(err);
            res.sendStatus(500);
            user = rows.map((row) => {
                return {};
            });
        }
        else {
            user = rows.map((row) => {
                return { name: row.name, id: row.id };
            });          
        }
        return user;
    });        
}

我做错了什么?或执行此操作的最佳方法是什么?

更新:稍微了解一下异步调用,就可以像这样重构我的代码,但是我仍然无法使它工作。 console.log给我“ AA”,“ BB”未定义,“ CC”上没有任何内容

router.get("/users/:id", (req, res) => {    
    const userId = req.params.id;
    const newLocal = "SELECT * FROM Users WHERE id = ?";
    selectUserById(newLocal, userId, res, function(users){
        console.log("CC "+users);
        res.end();
    });

    // if users==[]
       //user not found
    //else
       //res.render("users/showUser.ejs", {user: user});
});

function selectUserById(newLocal, userId, res) {
    var user;
    getConnection().query(newLocal, [userId], (err, rows, fields) => {
        if (err) {
            console.log(err);
            res.sendStatus(500);
            user = {}
        } else {
            user = rows.map((row) => {
                return { name: row.name, id: row.id };
            });          
        }
        console.log("AA "+user);
        return user;
    });     
    console.log("BB "+user);
    return user;
}

0 个答案:

没有答案