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.
via Biser Atanasov
No comments:
Post a Comment