我创建了一个使用nodemailer
发送电子邮件的函数,但是在运行控制台后,抛出了我:
TypeError: cb is not a function
at tryHandleCache (C:\Users\Maciek\Desktop\GoParty\backend\node_modules\ejs\lib\ejs.js:226:12)
at Object.exports.renderFile (C:\Users\Maciek\Desktop\GoParty\backend\node_modules\ejs\lib\ejs.js:437:10)
at Object.fn (C:\Users\Maciek\Desktop\GoParty\backend\api\controllers\user\create.js:47:28)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
我的sendEmails.js函数
const transporter = require('nodemailer').createTransport(sails.config.custom.email)
module.exports = {
inputs:{
to: { type:'string', required:true },
subject: { type:'string', required:true},
html: {type:'string', required:true}
},
exits:{
success: {
description: 'All done.'
}
},
fn: async function(inputs, exits){
const options = {
from: sails.config.custom.email.auth.user,
to: inputs.to,
subject: inputs.subject,
html: inputs.html
}
transporter.sendMail(options, (err, info) => {
if(err){
return exits.error(err)
}else return exits.success(info.response)
})
}
}
我的create.js,我必须在其中发送带有正确变量的电子邮件:
const ejsVariable = {
activeCode: inputs.activateCode
}
// const html = await ejs.renderFile(templatePath, ejsVariable)
// const subject = 'EventZone - potwierdzenie rejestracji'
// const res = await sails.helpers.email.sendEmail(inputs.email, subject, html)
// if(!res){
// return this.res.badRequest('Confirmation email has not been send.')
// }
感谢您的帮助
答案 0 :(得分:2)
ejs.renderFile
包含4个参数,最后一个是函数。用法示例:
ejs.renderFile(filename, data, options, function(err, str){
// str => Rendered HTML string
});
它不会返回承诺,所以您不能await
。
尝试替换
const html = await ejs.renderFile(templatePath, ejsVariable)
const subject = 'xxx'
const res = await sails.helpers.email.sendEmail(inputs.email, subject, html)
使用
ejs.renderFile(templatePath, ejsVariable, async (err, html) => {
const subject = 'xxx'
const res = await sails.helpers.email.sendEmail(inputs.email, subject, html)
})
更新
您可以使用util.promisify
来使ejs.renderFile
函数返回promise,从而像这样使用异步等待:
const util = require('util') //first import `util`
....
const asyncEjsRenderFile = util.promisify(ejs.renderFile)
const html = await asyncEjsRenderFile(templatePath, ejsVariable)
const subject = 'xxx'
const res = await sails.helpers.email.sendEmail(inputs.email, subject, html)