简体   繁体   中英

TypeError: callback is not a function - Node JS

I am learning Node js and I get following error when run the code.

TypeError: callback is not a function

Any help will be appreciated.

Following is my code

console.log('before');
getUser(1, getRepositories);
console.log('After');


function getRepositories(user) {
    getRepositories(user.gitHubUsername, getCommits);
}

function getCommits(repos) {
    getCommits(repos, displayCommits);
}

function displayCommits(commits) {
    console.log(commits);
}



function getUser(id, callback) {
    setTimeout(() => {
        console.log('Reading a user data from database...');
        callback({ id: id, gitHubUsername: 'Gary' });
    }, 2000);
}

function getRepositories(username, callback) {
    setTimeout(() => {
        console.log('Calling Github API....');
        callback(['repo1', 'repo2', 'repo3']);
    }, 2000);
}

that's because when you're calling callback from getUser you're expecting that getRepositories(user) is called but actually getRepositories(username, callback) is called. print username on the console so you'll know.

THERE'S NO OVERLOADING IN JAVASCRIPT.

So what you need to do is either change the function's name, or do something like

function getUser(id, callback) {
    setTimeout(() => {
        console.log('Reading a user data from database...');
        // callback({ id: id, gitHubUsername: 'Gary' });
        callback("Gary", getCommits);
    }, 2000);
}

On another note, your getCommits(repos) continuously calls itself without any base condition. you're likely to receive RangeError: Maximum call stack size exceeded .

You should have different functions name.

If you are new to nodeJs or JavaScript, Now a days you dont need to learn callback, specially you dont need to write your code in such a way where you provide function as a parameter(which you will call at the end of your function).

If you are pretty much familiar with the execution flow, You can write the functions sequentially instead of writing callbacks.

Even if any function is having asynchronous code then you can use Promises and make use of async/await functionality.

callback will make your code little complex and hard to debug.

This is my opinion. The javascript used to work perfectly over the time with callbacks, But with recent additions of Promise. async/await life becomes little easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM