Node.Js中的命名函数,以避免回调地狱不起作用

时间:2018-11-12 11:42:06

标签: node.js callback

我正在尝试使用命名函数技术解决回调地狱,但是回调无法正常工作。相反,错误表示TypeError: callback is not a function我正在提供以下代码,并在行中提供注释以显示错误行

function displayWorks(works) {

    console.log(`Username: ${works.user} has [${works.work}] works`);
}

function getWorks(user) {
    console.log("User", user);
    getWorks(user, displayWorks);
}

console.log("Before");
getUser(1, getWorks);
console.log("After");

function getUser(id, callback) {

    setTimeout(() => {
        console.log("Reading users from Database");
        callback({id: id, gitHubUserName: 'John Doe'}) // callback not working
    }, 2000);
}

function getRepositories(username, callback) {

    setTimeout(() => {
        console.log("Reading HowToWork.Com API");
        var works = {userName: username, works: ['work1', 'work2', 'work3']};
        callback(works); // not working
    }, 2000);
}

编辑1:我正在使用NodeJs v6.14.3版本。这是版本问题吗?

1 个答案:

答案 0 :(得分:0)

1)您在callWorks内部调用callWorks。也许您想改为调用getRepositories

2)您以错误的方式调用提供回调的callUser。

瞧瞧

function displayWorks(works) {

    console.log(`Username: ${works.user} has [${works.work}] works`);
}

function getWorks(user) {
    console.log("User", user);
    getRepositories(user.gitHubUserName, (works)=>{
        console.log(works)
    })
}

console.log("Before");
getUser(1, (user)=>{
    getWorks(user)
});
console.log("After");

function getUser(id, callback) {

    setTimeout(() => {
        console.log("Reading users from Database");
        callback({id: id, gitHubUserName: 'John Doe'}) // callback working
    }, 2000);
}

function getRepositories(username, callback) {

    setTimeout(() => {
        console.log("Reading HowToWork.Com API");
        var works = {userName: username, works: ['work1', 'work2', 'work3']};
        callback(works); // working
    }, 2000);
}