0

I was checking this sample on twilio docs (v2.x but v3.x also is similar and my question won't be altered).

// This example uses JavaScript language features present in Node.js 6+

'use strict';
const express = require('express');
const twilio = require('twilio');
const urlencoded = require('body-parser').urlencoded;

let app = express();

// Parse incoming POST params with Express middleware
app.use(urlencoded({ extended: false }));

// Create a route that will handle Twilio webhook requests, sent as an 
// HTTP POST to /voice in our application
app.post('/voice', (request, response) => {
  // Use the Twilio Node.js SDK to build an XML response
  let twiml = new twilio.TwimlResponse();

  // Use the <Gather> verb to collect user input 
  twiml.gather({ numDigits: 1 }, (gatherNode) => {
    gatherNode.say('For sales, press 1. For support, press 2.');
  });

  // If the user doesn't enter input, loop
  twiml.redirect('/voice');

  // Render the response as XML in reply to the webhook request
  response.type('text/xml');
  response.send(twiml.toString());
});

// Create an HTTP server and listen for requests on port 3000
app.listen(3000);

So here is the fragment below blocking?

twiml.gather({ numDigits: 1 }, (gatherNode) => { gatherNode.say('For sales, press 1. For support, press 2.'); }); If yes then assuming user enters something and we then move to twiml.redirect('/voice');

and other statements execute in sequence.

BUT if its non blocking, then /voice endpoint is called immediately and this continues in an infinite loop.

I was wondering how would the flow work.

EDIT:

The confusion seems to be caused by this comment // If the user doesn't enter input, loop

If user enters something then also twiml.redirect('/voice') is being called. I am not sure how does that code even work properly?

rahulserver
  • 10,411
  • 24
  • 90
  • 164

1 Answers1

1

Ricky from Twilio here.

This code doesn't create an infinite loop, but for a bit of a different reason than blocking vs non-blocking code. The way that you control a Twilio call flow is through TwiML, which is XML containing a set of instructions of what to do with an incoming call. The node code in your /voice route isn't handling the control flow itself, but generating XML that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Gather numDigits="1">
    <Say>For sales, press 1. For support, press 2.</Say>
  </Gather>
  <Redirect>/voice</Redirect>
</Response>
rickyrobinett
  • 1,224
  • 10
  • 13