【发布时间】:2014-11-05 17:00:36
【问题描述】:
我正在构建的一个网络应用程序将每三个月向客户发送一次发票。这将是一个在半夜运行的预定事件,但在开发过程中,我已将此代码放入路由中,以便对其进行测试。
简而言之,我希望代码执行以下操作。
- 从 DB 查询所有未发送的发票。
- 为每张发票调用 Mandrill(在此调用中,我还调用了一个函数,从发票创建 Mandrill 消息对象)。
- 对于 Mandrill 发送的每条消息,更新 DB 发票
sent: true。 - 发送完所有发票后,在
async.waterfall中进行最终回调
下面的代码有效。但我对_.each 有一些担忧。
invoices.post('/invoices/send/', function(req, res, next) {
async.waterfall([
// Query all unsent invoices
function(callback) {
db.invoices.find({sent: false}).toArray(callback);
},
// Send all unsent invoices
function(invoices, callback) {
if (invoices.length === 0) {
var err = new Error('There are no unsent invoices');
err.status = 400;
return next(err); //Quick escape if there are no matching invoice to process
}
// Make a call to Mandrill transactional email service for every invoice.
_.each(invoices, function(invoice) {
mandrillClient.messages.sendTemplate({template_name: "planpal-invoice", template_content: null, message: mandrillClient.createInvoiceMessage(invoice)}, function(sendResult) {
console.log(sendResult);
db.invoices.updateById(invoice._id, {$set: {sent: true}}, function(err, saveResult) {
console.log(saveResult);
});
}, function(err) {
return next(err);
});
});
callback(null, 'done');
}
],
function(err, result) {
if (err) {
return next(err);
}
res.json(result);
});
});
我想我应该改用async.eachLimit....但我不知道怎么写。
我不知道我应该设置什么限制,但我猜几个并行请求会比像上面那样运行所有 mandrill 请求更好,我错了吗? 编辑 _.each 并行运行回调。与async.each 的区别在于我没有得到“最终回调”
结论:我应该使用上面的async.eachLimit 吗?如果是,什么是好的限制值?
【问题讨论】:
标签: javascript node.js asynchronous mandrill