我想将值返回给变量,所以我尝试使用 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);
}
};
但是当运行回调示例时,我收到此错误
类型错误:回调不是函数
您以错误的方式使用回调。将回调传递给 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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句