[英]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.