我是nodejs编程的新手,我在nodejs和mysql中编写了一些其他api调用,我想通过nodejs mysql查询更新我的表但是在这里我面临着一些异步回调问题。我想连续执行查询.I尝试承诺也仍然是相同的结果
代码:
app.post("/storeData",function (req,response)
{
console.log(req);
var note = req.body.note;
var time = req.body.time;
var userid = req.body.userid;
var title = req.body.title;
var data = {
"code" : 0,
"message" : "fail"
};
if(note!=null && time!=null && userid!=null && title!=null)
{
var flag = checkIdExist(userid); // this one is executing async
if(!flag)
{
var query = "insert into todo values('',?,?,?,?)" ;
connection.query(query,[note,userid,title,time],function (err,rows,fields)
{
if(!err)
{
data.code = 200;
data.message = "success";
}
response.json(data);
});
}
});
}
else
{
data.code = 0;
data.message = "parameters are missing";
}
function checkIdExist(id)
{
var query = "select * from todo where userid = ? ";
connection.query(query,[id],function (err,rows,fields) {
if(err)
{
return false
}
else if(rows.length == 0)
{
return false
}
});
return true
}
答案 0 :(得分:0)
ES6已经建立了承诺。以下是如何使用ES6承诺同步或串行运行代码的演示。
app.post("/storeData", function(req, response) {
console.log(req);
var note = req.body.note;
var time = req.body.time;
var userid = req.body.userid;
var title = req.body.title;
var data = {
"code": 0,
"message": "fail"
};
if (note != null && time != null && userid != null && title != null) {
var checkIdExist = function() {
return new Promise((resolve, reject) => {
checkIdExist(userid, resolve, reject); // this one is executing async
});
}
checkIdExist()
.then((flag) => {
if (!flag) {
var query = "insert into todo values('',?,?,?,?)";
connection.query(query, [note, userid, title, time], function(err, rows, fields) {
if (!err) {
data.code = 200;
data.message = "success";
}
response.json(data);
});
}
})
.catch((error) => {
console.log(error.message);
});
} else {
data.code = 0;
data.message = "parameters are missing";
}});
function checkIdExist(id, resolve, reject) {
var query = "select * from todo where userid = ? ";
connection.query(query, [id], function(err, rows, fields) {
if (err) {
reject(err.message)
} else if (rows.length == 0) {
resolve(false);
}
});
resolve(true);}