-1

I'd like to be able to send a Sid to a number and have the function used for that number retrieve the information for that Sid. Specifically, I'd like to be able to retrieve the 'from' phone number for that specific SMS message (determined by the Sid). I can't seem to get anything more than the AccountSid and Sid from the fetch call.

What I have so far (modified for simplicity of this question):

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

What am I doing wrong or need to do in order to get the details of the message with the "sid"?

1 Answers1

0

Twilio developer evangelist here.

I think the problem you have here is a race condition. Making the API request against the Twilio API is an asynchronous request, your code notes that it is a promise, however before the promise is resolved you have called the callback function, which responds to the incoming request and terminates the function including any running asynchronous requests.

You will need to wait for the API request promise to resolve before calling the callback. Try something like this:

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

In the code above, the callback isn't called until the promise resolves or rejects.

philnash
  • 70,667
  • 10
  • 60
  • 88