I'm starting in node
and I still find the concept of asynchronous functions complicated. I'm using js
to render templates
to email in my application.
The prototype is:
"use strict";
const nodemailer = require('nodemailer');
const path = require('path');
const ejs = require('ejs');
function EmailManager(){
this.configs ={};
this.receivers = "";
this.subject = "";
this.template="";
this.context ={};
};
EmailManager.prototype.send = function(){
ejs.renderFile(path.join(__dirname,'..','templates',this.template),this.context, function(err, data) {
if(err){
throw err;
}
var transporter = nodemailer.createTransport(this.configs);
var mailOptions = {
from: '"'+ this.configs.sender
+ ' <'+ this.configs.user +'>', // sender address
to: this.receivers, // list of receivers
subject: this.subject,
};
mailOptions.html = data;
transporter.sendMail(mailOptions, function(error, info){
if(error){
throw error;
}
//console.log('Message sent to '+ this.receivers+", subject: "+ this.subject);
});
});
};
To run, I create a new instance, set all internal variables, and then run send()
. However, when I run the following error message appears:
TypeError error: Can not read property 'configs' of undefined (node: 9820) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): TypeError: Can not read property 'configs' of undefined
It seems that the reference this
is lost inside the asynchronous function, I read that functions of the type disregard the external context. So how could I pass this reference to my method? I also had this same problem with other similar functions.