为什么此代码会发送重复的电子邮件?

时间:2016-02-01 17:14:16

标签: node.js email azure sendgrid

我们在Azure上运行调度程序,每分钟运行一次并检查数据库,以查看需要为我们的应用程序发送哪些电子邮件并发送它们。

这绝大多数时间都有效,但偶尔会有几个小时,调度程序开始重复发送大多数电子邮件(最多5份)。

    query = "select id, email, textbody, htmlbody, subject from emailTable where sent = 0 AND DateSent IS NULL";
mssql.query(query, {
    success: function(results) {
        for(var i = 0 ; i < results.length; i++)
        {
            handleItem(results[i]);
        }
    },
    error: function(err) {
        console.log("Error : " + err);
    }
});

function handleItem(item) {
        sendMail(item); 
        var query = "update emailTable SET sent = 1, DateSent = GETDATE() where id = ?";
        mssql.query(query, [item.id]);

}

function sendMail(objMail)
{
    sendgrid.send({
      to:       objMail.email,
      from:     'source@sourcemail.com',
      fromname: "Source",
      subject:  objMail.subject,
      text:     objMail.textbody,
      html:     objMail.htmlbody
    }, function(err, json) {
      if (err) { return console.error(err); }
    });
}

当它开始失败时,就像同一项目多次调用handleItemsendMail一样。循环或解释这种行为的一般逻辑有什么问题吗?

1 个答案:

答案 0 :(得分:0)

Try writing the update query in the callback function for sendMail(item)

eg. sendMail(item,function(){
 var query = "update emailTable SET sent = 1, DateSent = GETDATE() where id = ?";
        mssql.query(query, [item.id]);
});

function sendMail(objMail,cb)
{
    sendgrid.send({
      to:       objMail.email,
      from:     'source@sourcemail.com',
      fromname: "Source",
      subject:  objMail.subject,
      text:     objMail.textbody,
      html:     objMail.htmlbody
    }, function(err, json) {
      if (err) { cb(err) }
       cb(null,json)
    });
}