首页 > 解决方案 > 呈现多个 NodeJs 查询的问题

问题描述

我正在尝试使用 Nodejs 在视图中呈现多个查询,但控制台返回 Promise {pending }。

请帮忙,我不知道我做错了什么。

router.get('/edit/:id', function (req, res, next) {
const{id} = req.params;
const linksUpdate = db.query('SELECT L.id,L.title,L.url,L.description,U.fullname,U.id FROM links AS L INNER JOIN users AS U ON L.user_id=U.id WHERE L.id = ?'[id], (error, results, fields) => {
if (error) throw error;
const users = db.query("SELECT U.id, U.username, U.password, U.fullname FROM users AS U", (error, resp, 
fields) => { if (error) throw error;
  console.log(linksUpdate);
  console.log(users);
   res.render('links/edit', {linksUpdate: linksUpdate,users: users
     });
        });
    });
});

标签: javascriptmysqlnode.jsexpress

解决方案


您需要在db.query()like的回调中移动您的逻辑

router.get('/edit/:id', function(req, res, next) {
   const { id } = req.params;
   db.query('SELECT L.id,L.title,L.url,L.description,U.fullname,U.id FROM links AS L INNER JOIN users AS U ON L.user_id=U.id WHERE L.id = ?' [id], (error, linksUpdate) => {
        if (error) return next(err);
        db.query("SELECT U.id, U.username, U.password, U.fullname FROM users AS U", (error, users) => {
            if (error) return next(err);
            console.log(linksUpdate);
            console.log(users);
            res.render('links/edit', {
                linksUpdate: linksUpdate,
                users: users
            });
        });
    });
});

或等待返回的承诺,而不是使用回调,如此处详细说明:https ://codeburst.io/node-js-mysql-and-async-await-6fb25b01b628


推荐阅读