Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert this function to not use the Promise constructor antipattern

I asked this question and was told to avoid the Promise constructor anti-pattern. I read through the article linked but I am unsure how to not use the anti pattern. This is the function:

db.getUserCount = function () {
    return new Promise (function (resolve, reject) {
    db.users.count().then(function (result) {
        resolve (result);
    }, function(e) {
        reject (e);
    });
});

I have all my database queries coded like the one above. This is my attempt to not use the anti-pattern but as I don't totally understand it I don't think this way is correct either:

db.getUserCount = function () {
    return new Promise (function (resolve, reject) {
        db.users.count().then(function (result) {
            return (result);
        }).then(function(result) {
            resolve(result);
        }).catch(function(err) {
            reject(err);
        });
    });
};

As I want to be writing good code, if someone could take a minute to show me an example of using the above function by not using the anti-pattern that would be great.

like image 911
nasoj1100 Avatar asked Dec 06 '25 07:12

nasoj1100


1 Answers

Since db.users.count() seems to return a promise already, you can just do this:

db.getUserCount = function () {
    return db.users.count();
});

There's not need to wrap it in an additional promise (using new Promise(...)).

like image 135
robertklep Avatar answered Dec 08 '25 19:12

robertklep