Search code examples
javascriptnode.jses6-promise

why chaining the promise doesn't work?


I don't understand why this code block throws the error :

Cannot read property 'then' of undefined

bcrypt.genSalt(10,(err, salt) =>{
    if(err){
        console.log(err);
    }
    return bcrypt.hash(password,salt); 
}).then((hash)=>console.log(hash));

when this successfully logs the hash

bcrypt.genSalt(10,(err, salt) =>{
    if(err){
        console.log(err);
    }
    bcrypt.hash(password,salt).then((hash) => console.log(hash));
});

since bcrypt.hash returns - Promise<string> shouldn't both these code blocks supposed to work(log hash) ?

thanks !


Solution

  • From the docs:

    Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.

    So just omit the callback and use then instead:

    bcrypt.genSalt(10).then(salt => {
        return bcrypt.hash(password,salt); 
    }).then(hash => {
        console.log(hash);
    }, err => {
        console.log(err);
    });