[英]Return value for main function from a callback function
所以我正在使用快速路由來處理獲取請求。 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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.