I am trying to get a list of users from a database and when this has pleted I want to list these users. I have tried to use a callback but getting the error that 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));
I am trying to get a list of users from a database and when this has pleted I want to list these users. I have tried to use a callback but getting the error that 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));
Share
Improve this question
asked Feb 1, 2017 at 14:13
user6002037user6002037
4
- 1 Try: checkForUsers('users', getAllUsers); – Ofir Baruch Commented Feb 1, 2017 at 14:14
- Would it be ok if I add it as an answer? – Ofir Baruch Commented Feb 1, 2017 at 14:16
- sure please do. i will give you the green tick. can you explain why you don't need to pass the argument? – user6002037 Commented Feb 1, 2017 at 14:18
- added an answer with an explanation. – Ofir Baruch Commented Feb 1, 2017 at 14:24
1 Answer
Reset to default 9Instead 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.
Source