Javascript 类型错误:cb 不是函数 - 带回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41981900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: cb is not a function - with callback
提问by Ofir Baruch
I am trying to get a list of users from a database and when this has completed I want to list these users. I have tried to use a callback but getting the error that TypeError: cb is not a function
我正在尝试从数据库中获取用户列表,完成后我想列出这些用户。我尝试使用回调,但收到错误TypeError: cb is not a function
var getAllUsers = function(users) {
console.log(users)
}
function checkForUsers(table, cb) {
connection.query('SELECT * from ' + table, function(err, rows, fields) {
if(err) console.log(err);
for(var i = 0; i < rows.length; i++) {
users.push({id: id});
if(i == (rows.length - 1)) {
cb(users)
}
}
});
}
checkForUsers('users',getAllUsers(users));
回答by Ofir Baruch
Instead of:
代替:
checkForUsers('users',getAllUsers(users));
Use:
用:
checkForUsers('users',getAllUsers);
The reason emphasised:
理由强调:
We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren't passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.
我们可以像变量一样传递函数并在函数中返回它们并在其他函数中使用它们。当我们将回调函数作为参数传递给另一个函数时,我们只是传递了函数定义。我们没有执行参数中的函数。换句话说,我们不像在执行函数时那样传递带有尾随一对执行括号 () 的函数。

