我想将值返回到varibales,所以我尝试使用return来编写它,但是确实没有工作
class move {
getLastMove(id){
var MoveRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(MoveRequest, function(err,rows, result) {
//console.log('rows', rows.length);
if (rows.length == 0) { // evaluate the count
return ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
console.log('getLastMove',id);
var move = rows[i].MoveString;
if (rows[i].GameId == id){
return move;
}
}
}
//console.log("Total Records:- " + result[0].total);
});
var move="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return move;
}
};
所以我试着像这样使用回调
class move {
getLastMove(id){
var MoveRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(MoveRequest, function(err,rows, result,callback) {
//console.log('rows', rows.length);
if (rows.length == 0) { // evaluate the count
callback ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
console.log('getLastMove',id);
var move = rows[i].MoveString;
if (rows[i].GameId == id){
callback(move);
}
}
}
//console.log("Total Records:- " + result[0].total);
});
var move="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
callback(move);
}
};
但是当运行回调示例时我得到此错误
TypeError:回调不是函数
答案 0 :(得分:2)
class move {
getLastMove(id,callback){
var query = connection.query(MoveRequest, function(err,rows, result) {
//do some operation then
if (rows.length > 0) {
for (var i in rows) {
console.log('getLastMove',id);
var move = rows[i].MoveString;
if (rows[i].GameId == id){
callback(err,move) //<-------
}
}
}
});
}
};
var moveInstance = new move();
moveInstance.getLastMove(id,function(err,result){ //code here })
答案 1 :(得分:0)
你以错误的方式使用回调。将回调传递给getLastMove():
class move {
getLastMove(id, callback){
var MoveRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(MoveRequest, function(err,rows, result) {
if(err) {
return callback(err)
}
if (rows.length == 0) { // evaluate the count
return callback (null, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
if (rows[i].GameId == id){
callback(null, rows[i].MoveString);
}
}
}
});
}
};
假设moveObj
是move
类型的对象,请调用函数getLastMove
,如:
var moveObj = new move();
moveObj.getLastMove(34, function (err, data) { // 34 is the value of `id`
if(err) {
// There was some error in execution of getLastMove; var `err` has info regarading that.
return console.log("There was some err while executing getLastMove", err);
}
// If no Error, process your `data` accordingly
console.log("Data returned by callback", data);
});