【发布时间】:2018-07-18 01:24:12
【问题描述】:
以下代码有效:
var smtpConfig = {
host: 'localhost',
port: 465,
secure: true, // use SSL
selfSigned: true
};
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpConfig);
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"Some One" <someone@example.com>', // sender address
to: 'validuser@company.com', // list of receivers
subject: 'Hello', // Subject line
text: 'Hello world ?', // plaintext body
html: '<b>Hello world ?</b>' // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log(info);
}
});
但是,如果我从节点使用util.promisify
var sendMail = promisify(transporter.sendMail);
var info = await sendMail(mailOptions);
我遇到了异常
TypeError: Cannot read property 'getSocket' of undefined
at sendMail (c:\Users\user\Source\project\node_modules\nodemailer\lib\mailer\index.js:143:25)
at sendMail (internal/util.js:230:26)
问题在 sendMail 内部,因为 'this' 未定义:
/**
* Sends an email using the preselected transport object
*
* @param {Object} data E-data description
* @param {Function?} callback Callback to run once the sending succeeded or failed
*/
sendMail(data, callback) {
let promise;
if (!callback && typeof Promise === 'function') {
promise = new Promise((resolve, reject) => {
callback = shared.callbackPromise(resolve, reject);
});
}
if (typeof this.getSocket === 'function') { <-- this is undefined
this.transporter.getSocket = this.getSocket;
this.getSocket = false;
}
在普通函数上使用 util.promisify 是可行的。我想这是因为我在类方法上使用了util.promisify。
有没有办法实现这一点,或者我是否需要使用 async function sendMail 重载扩展 exting 类
【问题讨论】:
-
util.promisify不可能知道sendMail之前附加到的对象。 -
您在滥用
promisify。如果您想以您尝试的方式使用它,您将需要绑定上下文。promisify非常适合不需要状态的函数式函数。
标签: node.js typescript async-await es6-promise nodemailer