最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: cb is not a function - with callback - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 9

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.

Source

发布评论

评论列表(0)

  1. 暂无评论