2

I created a function that find documents in my db. It is a custom function and Im going to pass values to its parameter in my controller. Then I want to use .then() after. Here is my code.

custom function

  getProjectsList(userId) {
    const query = { users: { $in: [userId] }, isDeleted: false };
    Project.find(query);
  },

and in my controller

projectsList(req, res) {
  projectModule.getProjectsList(req.user.id)
    .then(() => {   // this is not recognized
         // do something here
    });
},

Please help. I tried something like this but it doesn't work

getProjectsList(userId) {
 return new Promise(() => {
  const query = { users: { $in: [userId] }, isDeleted: false };
  Project.find(query);
 });
},

2 Answers2

1

The Project.find() method must be returning a callback or a promise. Let's assume that it is returning a promise so the code for Project.find() will be

Project.find(query)
.then(function(result){// success handling})
.catch(function(error){ //error handling })

Now you want to create a new function getProjectsList as a promise and put Project.find() inside it.

So that can be written as

function getProjectsList(userId){
      return new Promise(function(resolve,reject){

                Project.find(query)
                .then(function(result){
                      // success handling
                      resolve(result);
                  })
                .catch(function(error){ 
                     //error handling
                     reject(error);
                 })
      })
}
selftaught91
  • 7,013
  • 3
  • 20
  • 26
  • This promotes the [promise constructor anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). – trincot May 31 '17 at 04:47
  • But this pattern is helpful when you want to perform some business logic to the response and keeping the main code flow clean @trincot – selftaught91 May 31 '17 at 05:00
  • I would not call this *clean*. It is called an anti-pattern for a reason. There is *never* a good reason to abuse the promise constructor like that. – trincot May 31 '17 at 05:15
-1

you can use callback function. try this

projectsList(req, res) {

projectModule.getProjectsList(req.user.id, function(err, result){

if(err){
    res.json({
        "result" : "failure"
    });
}

    res.json({
        "result" : "success"
    });
});
};

get project list function here

getProjectsList(userId, callback) {

const query = { users: { $in: [userId] }, isDeleted: false };

Project.find(query, function(err, result){
    if(err){
        return callback(err);
    }

    callback(null, result);

});
};