简体   繁体   中英

callback is not a function for async operations using nodejs

index.js:

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

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

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

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

function getCommits(repo,callback) {
    setTimeout(() => {
        console.log('Getting commits for a GitHub repo...');
        callback(['commit1', 'commit2', 'commit3']);
    }, 2000)
}

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

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

I navigated to the path containing the file and executed the command: node index.js and got the error: callback is not a function.

Can anyone guide me here to fix this issue?

Here is the updated code with the fix:

index.js:

console.log('Before');
getUser(1, getRepositorie);
console.log('After');

function getRepositorie(user) {
    getRepositories(user.gitHubUsername, getCommit);
}

function getCommit(repos) {
    getCommits(repos[0], displayCommits);
}

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

function getCommits(repo,callback) {
    setTimeout(() => {
        console.log('Getting commits for a GitHub repo...');
        callback(['commit1', 'commit2', 'commit3']);
    }, 2000)
}

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

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

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