如何通过 Twilio 函数正确循环发送短信

How to properly Loop through SMS sending via Twilio Functions

我让 Twilio Studio 调用 Twilio 函数,并需要它将电子邮件发送到电子邮件的可变列表(小列表)。这个问题主要是围绕它们循环,因为我可以很好地传递变量。我有一系列电子邮件可以发送文本到 Twilio 函数中。但是我在网上找到的所有例子都是关于只发送给一个。我的一部分认为这需要是一个调用另一个 Twilio 函数的 Twilio 函数(一个循环,另一个发送电子邮件)......但我想不出一种方法来做到这一点。如果我可以将它包含在一个 Twilio 函数中,那就太好了。

我让 Twilio Studio 调用 Twilio 函数。我需要将所有这些都保存在 Twilio 上...因此通过 PHP 和 运行ning 功能一次一个地循环通过那里是行不通的。我需要这个 运行 Twilio 的无服务器设置。

这是我的一个有效示例:

exports.handler = function(context, event, callback) {
    // using SendGrid's v3 Node.js Library
    // https://github.com/sendgrid/sendgrid-nodejs
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(context.SENDGRID_API_KEY);
    const msg = {
      to: 'me@example.com',
      from: 'noreply@example.com',
      templateId: 'my-id-goes-here',
      dynamic_template_data: {
        recipient_name: 'John Smith'
      }
    };
    sgMail.send(msg).then(response => {
      let twiml = new Twilio.twiml.MessagingResponse();
      callback(null, twiml);
    })
    .catch(err => {
      callback(err);
    });
};

这是我尝试以类似的方式循环但失败了

exports.handler = function(context, event, callback) {
    const sgMail = require('@sendgrid/mail');

    sgMail.setApiKey(context.SENDGRID_API_KEY);

    var responder_emails = 'me@example.com,me+test1@example.com';
    var emails_a = responder_emails.split(',');

    emails_a.forEach(function(responder_email) {
        const msg = {
          to: responder_email,
          from: 'noreply@example.com',
          templateId: 'my-id-goes-here',
          dynamic_template_data: {
            recipient_name: 'John Smith'
          }
        };
        sgMail.send(msg);
    });

    callback();
};

我可以将多封电子邮件传入 Twilio 函数...我只是不确定如何正确循环。

嘿嘿。 Twilio 传播者在这里。

在您的第一个示例中,您正确地使用 then 等待 send 调用完成。在你的第二个例子中,你错过了。您 运行 多次 send 呼叫,但立即呼叫 callback 而无需等待。

固定的(大致原型版本)可能如下所示。

exports.handler = function(context, event, callback) {
  const sgMail = require('@sendgrid/mail');

  sgMail.setApiKey(context.SENDGRID_API_KEY);

  var responder_emails = 'me@example.com,me+test1@example.com';
  var emails_a = responder_emails.split(',');

  Promise.all(emails_a.map(function(responder_email) {
    const msg = {
      to: responder_email,
      from: 'noreply@example.com',
      templateId: 'my-id-goes-here',
      dynamic_template_data: {
        recipient_name: 'John Smith'
      }
    };
    return sgMail.send(msg);
  })).then(function() {
    callback();
  }).catch(function(e) {
    callback(e);
  })
});

因为您调用了 split,所以您已经收到了一系列电子邮件。您可以将此数组与 Array.mapPromise.all 结合使用。

Map 基本上遍历您的数组,并允许您使用 map 内部函数 return 中的任何内容创建一个新数组。上面的代码所做的是将 [email, email] 转换为 [Promise, Promise]。承诺是 sgMail.send 的 return 值。

现在,您有一个数组,其中包含将在 sendgrid 接受您的呼叫时解析的承诺,您可以使用 Promise.all。此方法等待所有承诺被解决(或拒绝)并且 return 本身是一个新的承诺,您可以将其与 then 一起使用。完成所有 sendgrid 调用后,就可以通过调用函数 callback.

来完成该函数了

旁注:此 "map/Promise.all" 技巧并行执行所有发送网格调用。在某些情况下,您可能想调用它们 one after another(也就是说您正在进行大量调用并且 运行 进入速率限制)。

希望对您有所帮助,让我知道进展如何。 :)