Don't use util.promisify

Don't use util.promisify

without setting the `this` context.

·

1 min read

Many developers use util.promisify() without hesitation when they need to convert the callback method to a promise based method.

But there is a catch. util.promisify() changes this context to golbalThis. So if the actual method is using this somewhere in the code, it will fail/produce undesired results.

mailer.sendSMTP = function(message, cb){
        // some code 
        this.smtpTransport.sendMail(message , cb);
    };

The above code will work perfectly fine when it is invoked with a callback fn. But when its promised as follows then it will throw TypeError: Cannot read property 'sendMail' of undefined

 try {
        emailResult = await promisify(mailer.sendSMTP)(emailToSend);
    } catch (error) {
        throw `Error while sending email: ${error}`;
    }

it can be fixed either by binding the context again or changing the implementation.

Binding the context using call, apply or bind methods

try {
        emailResult = await promisify(mailer.sendSMTP).call(mailer,emailToSend);
    } catch (error) {
        throw `Error while sending email: ${error}`;
    }

Moving the context variable outside of the method.

var _that = mailer; 
mailer.sendSMTP = function(message, cb){
        // some code 
        _that.smtpTransport.sendMail(message , cb);
    };

References: github.com/nodejs/node/issues/13338