
如图,我用的express框架,写的一个路由,把
app.get("/loginForm?**", function (req, res) {
pool.getConnection(function (err) {
if (err) { }
else {
connection.query("USE userInfo", function (err, rows) {
//业务逻辑
});
}
});
});
改写为step模式,即使用中间函数传递值,也没法把req和res传递到最内层connection.query的回调函数里,但是这里业务逻辑会用到res.send()向前端传数据,所以问题来了,怎么跨层传递这个res呢?
有人说直接用就行,我改写了代码如下
step(
function appGet() {
app.get("/loginForm?**", this);
},
function poolGet(err, req, res) {
pool.getConnection(this);
},
function poolUse(err, connection, req, res) {
console.log(p);
if (err) {
console.log(err + "--from connection");
res.send("登录失败,数据库连接错误");
} else {
var queryString = "USE userInfo;";
connection.query(queryString, this);
}
},
function poolSelect(err, rows) {
if (err) {
console.log(err);
} else {
var selectQuery = "SELECT * FROM users WHERE userName=" + "'" + req.query.username + "'";
connection.query(selectQuery, this);
}
},
function poolRows(err, rows) {
if (err) {
console.log(err + "--from queryString");
res.send("登录失败,数据库查询错误");
} else {
if (rows.length == 0) {
res.send("登录失败,用户不存在");
} else {
if (req.query.password == rows[0].password) {
res.cookie("username", req.query.username, {
expires: new Date(Date.now() + 900000)
});
res.send("登录成功");
} else {
res.send("登录失败,密码不正确");
}
}
}
});
select那层调用connection,还有最内层调用res,req都是undifined
我之前写return是因为this无法传递值,试试return行不行
根据大神的指点,我试了下parallel形式,代码如下
step( function appGet(){
app.get("/loginForm?**",this.parallel());
pool.getConnection(this.parallel());
},
function poolUse(req,res,connection,err){
if (err){
console.log(err+"--from connection");
res.send("登录失败,数据库连接错误");
}else{
var queryString = "USE userInfo";
connection.query(queryString,function(err,rows){
if (err) {
console.log(err);
} else{
res.send(rows);
}
});
}
}
);
服务器可以返回数据,然而,如你所见,内层的connection.query就只能写成回调风格了,因为如果你写成this或者别的什么,app.get的res和req就传进去了
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
时隔半年,回头看自己的代码真是too young,一个promise可以解决的问题