Javascript 回调函数中主函数的返回值

Javascript 回调函数中主函数的返回值,javascript,express,ejs,Javascript,Express,Ejs,因此,我使用快速路由来处理get请求。get请求最终将调用处理发送电子邮件的函数。我正在试图弄清楚,如果其中一个文件加载失败,如何防止函数继续 路由逻辑: app.get('/example',sendEmail,function(req,res){ //Code that runs before calling my sendEmail function var results = sendEmail("example.com"); // Check if sendi

因此,我使用快速路由来处理get请求。get请求最终将调用处理发送电子邮件的函数。我正在试图弄清楚,如果其中一个文件加载失败,如何防止函数继续

路由逻辑:

app.get('/example',sendEmail,function(req,res){
    //Code that runs before calling my sendEmail function

    var results = sendEmail("example.com");

   // Check if sending the email was successful or threw an error.
});
电子邮件/EJS逻辑:

function sendEmail(emailAddress){
    var emailTEXT = ejs.renderFile('TEXT.ejs', function(err,file){
        if(err){
            console.log(err);
            // break out of the sendEmail function by returning data
        } else {
            return file // Return this value to the variable and continue on with the function.
        }
    );
    var emailHTML = ejs.renderFile('HTML.ejs', function(err,file){
        if(err){
            console.log(err);
            // break out of the sendEmail function by returning data
        } else {
            return file // Return this value to the variable and continue on with the function.
        }
    );

    // Code to send email with the HTML and TEXT version of the email.
}

我知道我可以在出错时返回一个空白字符串,并在每个变量后检查它,但必须有一种更简单的方法来实现这一点

您可以尝试以下方法:

function sendEmail(emailAddress){
    var emailTEXT = new EJS({url: 'TEXT.ejs'}).render(/* Some data */);
    var emailHTML = new EJS({url: 'HTML.ejs'}).render(/* Some data */);

    // Code to send email with the HTML and TEXT version of the email.
}

我使用的是ejs的节点版本,因此我认为这不会起作用,因为没有定义“ejs”。我有
var ejs=require('ejs')也在文件中。我明天早上试试看是否有效。