0

I'm trying to refactor my code, because I want to have fewer callbacks in my code. And I want to display the obj variable again in the console. But I can't get it to manage it somehow.

Here is the output that I see in my console:

getProjectsByRole
obj stringfy  = {
    "emitter": {
        "domain": null,
        "_events": {},
        "_eventsCount": 2
    },
    "emitted": {},
    "ended": false
}

And here is my code:

router.get('/projects', function (req, res) { 
    //Some code..

    var obj = getProjectsByRole(req.session.user.role);
    console.log("obj stringfy  = " +JSON.stringify(obj, null, 4));
    res.status(200).json(obj);
}

function getProjectsByRole(role) {
    console.log("getProjectsByRole");
    var promise = Project.find({ roles : { name : role} }).exec();

    promise.then(getCurrentProjects).catch(function(err){
        console.log('error man :', err);
    });

    return promise;
}

function getCurrentProjects(err, currentProjects) {

    console.log("getCurrentProjects()  currentProjects stringfy  = " +JSON.stringify(currentProjects, null, 4));
    if (currentProjects !== null) {
        if (err) console.log("een error " + err);

        // var promise = Project.count({}, countProjects).exec();
        var promise = Project.count({}).exec();
        return promise.then(countProjects);

    } else {
        console.log("no projects found");
        return false;
    }
}

function countProjects(err, count){
    console.log("countProjects() ");
    var obj = {
        totalItems: count,
        items: currentProjects
    }
    console.log("countProjects() count stringfy  = "+ JSON.stringify(count, null, 4));
    return obj;
}

I'm using mongoose 4.5.2.

superkytoz
  • 1,267
  • 4
  • 23
  • 43
  • A ["thenable"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) has one argument to the function. Should be `function getCurrentProjects(currentProjects)`, otherwise you are actually passing the promise result into `err` instead of `currentProjects` like you intend to. Same for the other function you are passing. Promises don't use the same nodejs callback style of "error first". – Neil Lunn Oct 27 '17 at 22:57
  • In actual fact the "error handler" is a "second" function, but is "aliased" with [`.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch). All in the documenation. – Neil Lunn Oct 27 '17 at 23:00

0 Answers0