![](/img/trans.png)
[英]How to wait for a loop to finish running before sending back a response in NodeJs?
[英]How do you wait for a delivery response from Mandrill before sending response back to client?
我正在用Koa和Node 0.11構建一個簡單的服務器。 我希望當用戶從我的站點提交查詢時向我發送電子郵件。 當然,如果電子郵件由於任何原因未能發送,我想提醒用戶,但是我不確定“等待”發生的最佳方法。
我相關的服務器代碼非常簡單:
app.put('/inquiry', function *() {
var status = yield sendEmail('test', "my message", "me@mysite" );
this.body = status;
});
function sendEmail(subject, message, to) {
var fromEmail = 'you@yoursite.com';
var tags = ['subject'];
var to = {email: to};
return function() {
mandrill('/messages/send',
{
message: {
"from_email":fromEmail,
"to":[to],
"text":message,
"tags":tags
}
},
function (error, response) {
if (error) {
console.log(JSON.stringify(error));
return error;
}
else {
console.log("Mandrill result: "+response);
return response;
}
};
);
};
};
我遇到的問題是Mandrill.send()函數沒有返回任何內容,而且我不確定最好的方法是什么。
您只需要將其包裝在一個匿名函數中,如下所示:
function sendEmail(subject, message) {
var fromEmail = 'test@elliottregan.com';
var tags = ['subject'];
var to = {email:'oatmealsnap@gmail.com'};
return function(callback) {
mandrill('/messages/send', {
message: {
"from_email":fromEmail,
"to":[to],
"text":message,
"tags":tags
}
},
function (error, response) {
if (error) {
console.log(JSON.stringify(error));
return error;
}
else {
console.log("Mandrill result: "+response);
callback(null, response);
}
}
)}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.