首页 > 解决方案 > Nodemailer - cb is not a function?

问题描述

i create an function to send email with nodemailer, but after run my console throw me:

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)

my function to 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)
        })
    }
}

my create.js where i must send email with correct variables:


    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.')
    // }

thanks for any help

标签: javascriptnode.js

解决方案


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函数返回一个承诺,从而像这样使用 async await:

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)

推荐阅读