Biser A.
Biser A.

Reputation: 154

Bad patterns when writing promises?

I'm wondering if I'm using bad practices when writing custom promises.

I have the following situation.

generateHash(password){
    return new Promise((resolve, reject) => {
        bcrypt.genSalt(10).then(salt => {
            bcrypt.hash(password, salt).then(hash => {
                resolve(hash)
            }).catch(reject)
        }).catch(reject)
    })
}

generateHash() has to return a promise which contains the hashed password. .genSalt() returns a promise and so does .hash(). What I need is generateHash() to return the promise returned by .hash() but since it's inside .genSalt() such thing doesn't happen. I figured that if the function returns a custom promise and everything sits inside it would work perfectly and it did, but I'm wondering if nesting promises like that is a bad practice and a terrible idea overall.

Another thing that I did is approach it more traditional way by using callbacks like so:

return new Promise((resolve, reject) => {
        bcrypt.genSalt(10, function (err, salt) {
            bcrypt.hash(password, salt, function (err, hash) {
                if (err) return reject(err)
                resolve(hash)
            });
        });
    })

I'm open to suggestions which way is better and kind of want to stick with promises so ideas on how to do that with promises the best way possible are greatly appreciated.

Upvotes: 0

Views: 188

Answers (2)

Sirko
Sirko

Reputation: 74036

Why do you nest promises into promises?

You could just do

generateHash(password){
    return bcrypt.genSalt(10)
                 .then(salt => bcrypt.hash(password, salt) )
}

Upvotes: 1

baao
baao

Reputation: 73231

There's no need to create your own promise when the method you are using already returns a promise. The following code will log the generated hash to the console, without creating a promise by yourself:

const bcrypt = require("bcrypt")
function generateHash(password){
    return bcrypt.genSalt(10).then(salt => {
            return bcrypt.hash(password, salt).then(hash => {
                return hash;
            })
        })
}

generateHash("foo").then(v => console.log(v));

Note that you need to return the inner function - so basically, the code would boil down to

function generateHash(password){
    return bcrypt.genSalt(10).then(salt => bcrypt.hash(password, salt));
}

Upvotes: 1

Related Questions