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

问题描述 投票:0回答:3

我想过滤每个电话号码的短信和使用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]);
node.js rest twilio
3个回答
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);
 });

如果这有帮助,请告诉我。


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]);
}

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]);
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.