Twilio Node JS - 按电话号码过滤短信

时间:2018-03-02 20:46:28

标签: node.js rest twilio

我想过滤使用REST API发送短信的每个电话号码和日期的短信,但是以下代码的输出在client.messages.each()块之外是不可用的。 请告知我如何使用发送到过滤号码的最新短信代码:

const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
client.messages.each(filterOpts, (record) => {
  codeCollection.push(record.body.match(pattern)[0]);
  console.log(record.body.match(pattern)[0], record.dateSent);
 });
 console.log(codeCollection,'I get an empty array here');//how to get 
 the latest sms and use it 
 doSomethingWithSMS(codeCollection[0]);

3 个答案:

答案 0 :(得分:1)

Twilio开发者传道者在这里。

each function实际上并没有返回Promise。您可以在each完成流式搜索结果后运行回调函数,方法是将其作为done传递到选项中,如下所示:

const codeCollection = [];
const pattern = /([0-9]{1,})$/;

const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD'),
  done: (err) => {
    if (err) { console.error(err); return; }
    console.log(codeCollection);
    doSomethingWithSMS(codeCollection[0]);
  }
};

client.messages.each(filterOpts, (record) => {
  codeCollection.push(record.body.match(pattern)[0]);
  console.log(record.body.match(pattern)[0], record.dateSent);
 });

让我知道这是否有帮助。

答案 1 :(得分:0)

您是否可以访问消息数组的长度?如果是这样,你可以做这样的事情

const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
var i = 0
client.messages.each(filterOpts, (record) => {
    if (i < messages.length){
        codeCollection.push(record.body.match(pattern)[0]);
        console.log(record.body.match(pattern)[0], record.dateSent);
        i++;
    else {
        nextFunction(codeCollection);
    }
 });

function nextFunction(codeCollection){
     console.log(codeCollection,'I get an empty array here');
     doSomethingWithSMS(codeCollection[0]);
}

答案 2 :(得分:0)

messages.each()以异步方式运行,因此当client.messages()内容在后台线程上运行时,主线程将继续进行下一个调用。因此,在您尝试访问它时,没有任何内容被推送到codeCollection。在继续之前,您需要以某种方式等待each()完成。 Twilio客户端使用主干样式承诺,因此您只需添加另一个.then()链接到链,如下所示。您还可以使用像async这样的库,它允许您使用等待以更线性的方式编写异步代码。

const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
client.messages.each(filterOpts, (record) => {
    codeCollection.push(record.body.match(pattern)[0]);
    console.log(record.body.match(pattern)[0], record.dateSent);
}).then(
    function() {
        console.log(codeCollection,'I get an empty array here');
        if( codeCollection.count > 0 ) doSomethingWithSMS(codeCollection[0]);
    }
);