【问题标题】:How to fetch an SMS message's information (such as the from property) with its Sid?如何使用 Sid 获取 SMS 消息的信息(例如 from 属性)?
【发布时间】:2021-11-18 22:31:34
【问题描述】:

我希望能够向一个号码发送一个 Sid,并让用于该号码的函数检索该 Sid 的信息。具体来说,我希望能够检索该特定 SMS 消息(由 Sid 确定)的“发​​件人”电话号码。除了从 fetch 调用中得到的 AccountSid 和 Sid 之外,我似乎什么也得不到。

到目前为止我所拥有的(为了简化这个问题而进行了修改):

exports.handler = function(context, event, callback) {
  var Sid = event.Body;
   
  let client = context.getTwilioClient();
  // without the 'fetch()' it gets only the AccountSid and Sid, with the 'fetch()' it doesn't seem to get anything?  
  let promise = client.messages(`${Sid}`).fetch();
  var x;
  console.log(promise);
  // saw that it was returning a promise with the fetch so tried to use it here somehow, but nothing returned or worked
  promise.then(m => {
    x = m;
  });
  console.log(x);
  
  // do something, create a response message and send

  callback(null, twiml);
};

为了获取带有“sid”的消息的详细信息,我做错了什么或需要做什么?

【问题讨论】:

    标签: node.js twilio twilio-api twilio-twiml


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    我认为您在这里遇到的问题是竞争条件。针对 Twilio API 发出 API 请求是一个异步请求,您的代码指出它是一个 Promise,但是在解决 Promise 之前,您调用了 callback 函数,该函数响应传入请求并终止该函数,包括任何正在运行的异步请求。

    在调用 callback 之前,您需要等待 API 请求承诺解决。试试这样的:

    exports.handler = function(context, event, callback) {
      const sid = event.Body;
      const client = context.getTwilioClient();
    
      client.messages(sid).fetch()
        .then(message => {
          const twiml = new Twilio.twiml.MessagingResponse();
          twiml.message(`The message with sid ${sid} was sent by ${message.from}.`);
          callback(null, twiml);
        }).catch(error => {
          callback(error);
        });
    };
    

    在上面的代码中,callback 在 promise 解决或拒绝之前不会被调用。

    【讨论】:

    • 太棒了;这有效且有意义!谢谢!
    • 太棒了!如果它确实解决了问题,您是否介意将答案标记为正确,它可以帮助其他人看到它也有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多