Search code examples
javascriptecmascript-6promisees6-promise

Promise returning as a function when wrapping callback function


I'm trying to convert an existing callback based function from the crypto library to be used with es6 async/await in the method above it. Whenever I make a call to generateSubkey(password,salt) it returns [function]. Inside this if I call toString() it shows my methods code as opposed to executing it.

import crypto from 'crypto';
import Promise from 'bluebird';

async hashPassword(password) {

    try {
        // Create a salt with cryptographically secure method.
        let salt = await crypto.randomBytes(16);

        let subkey = await this.generateSubkey(password, salt);

        console.log(subkey);

    } catch (e) {

    }

}

generateSubkey(password, salt) {
    return new Promise.resolve((resolve, reject) => {
        return crypto.pbkdf2(password, salt, 10000, 32, 'sha256', (err, buffer) => {
            if (err) {
                reject();
            }
            resolve(buffer);
        });
    })
}

Solution

  • Whenever I make a call to generateSubkey(password,salt) it returns [function].

    To use the promise constructor with the executor callback, it's return new Promise(…), not return new Promise.resolve(…).

    I'm trying to convert an existing callback based function from the crypto library to be used with ES8 async/await

    You might be looking for util.promisify. No need to bring in Bluebird1 and use the new Promise constructor.

    import crypto from 'crypto';
    import util from 'util';
    
    const pbkdf2Async = util.promisify(crypto.pbkdf2);
    function generateSubkey(password, salt) {
        return pbkdf2Async(password, salt, 10000, 32, 'sha256');
    }
    

    1: If you still want to use Bluebird, it does bring a promisify function as well :-)