Twilio serverless function async operations execute order problem

What I’m trying to do:

  1. Incoming call from user would trigger a Digits Gather (No problem)
  2. After receiving the Digits, Say something to the user
  3. Play music while fetching phone number from an API using async/await
  4. Dial said phone number from API’s response.

My Code:

gather-extension.js (Gather and retry both work, thus not providing retry js)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>exports.handler = async (context, event, callback) => {
const retryMax = 2;
const twiml = new Twilio.twiml.VoiceResponse();
const gather = twiml.gather({
action: `./fetch-driver-phone`,
method: 'GET',
timeout: 2
});
gather.say('Thanks for calling');
//retry
twiml.redirect(`./retry-gather-ext?retry=1&retry_max=${retryMax}`);
return callback(null, twiml);
}
</code>
<code>exports.handler = async (context, event, callback) => { const retryMax = 2; const twiml = new Twilio.twiml.VoiceResponse(); const gather = twiml.gather({ action: `./fetch-driver-phone`, method: 'GET', timeout: 2 }); gather.say('Thanks for calling'); //retry twiml.redirect(`./retry-gather-ext?retry=1&retry_max=${retryMax}`); return callback(null, twiml); } </code>
exports.handler = async (context, event, callback) => {
  const retryMax = 2;
  const twiml = new Twilio.twiml.VoiceResponse();

  const gather = twiml.gather({
    action: `./fetch-driver-phone`,
    method: 'GET',
    timeout: 2
  });

  gather.say('Thanks for calling');
  //retry
  twiml.redirect(`./retry-gather-ext?retry=1&retry_max=${retryMax}`);

  return callback(null, twiml);
}

fetch-driver-phone.js (This is where the problem is)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>exports.handler = async (context, event, callback) => {
const twiml = new Twilio.twiml.VoiceResponse();
const callerPhoneNumber = event.From;
const extension = event.Digits;
console.log('Caller Phone Number:', callerPhoneNumber);
if (extension == null) {
//handle error
}
twiml.say("Please wait while we connect you");
twiml.play("http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3");
try {
console.log("Calling API");
const result = await fetchDriver(extension, twiml)
console.log(result);
twiml.dial().number(result);
callback(null, twiml);
} catch(error) {
console.error(error);
twiml.say('We are unable to process your request at this time.');
twiml.hangup();
callback(error);
}
}
const fetchDriver = async (code) => {
console.log('Extension Digits:', code);
return new Promise((resolve) => {
setTimeout(() => {
resolve('phone number');
}, 5000);
});
}
</code>
<code>exports.handler = async (context, event, callback) => { const twiml = new Twilio.twiml.VoiceResponse(); const callerPhoneNumber = event.From; const extension = event.Digits; console.log('Caller Phone Number:', callerPhoneNumber); if (extension == null) { //handle error } twiml.say("Please wait while we connect you"); twiml.play("http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3"); try { console.log("Calling API"); const result = await fetchDriver(extension, twiml) console.log(result); twiml.dial().number(result); callback(null, twiml); } catch(error) { console.error(error); twiml.say('We are unable to process your request at this time.'); twiml.hangup(); callback(error); } } const fetchDriver = async (code) => { console.log('Extension Digits:', code); return new Promise((resolve) => { setTimeout(() => { resolve('phone number'); }, 5000); }); } </code>
exports.handler = async (context, event, callback) => {
  const twiml = new Twilio.twiml.VoiceResponse();

  const callerPhoneNumber = event.From;
  const extension = event.Digits;

  console.log('Caller Phone Number:', callerPhoneNumber);

  if (extension == null) {
    //handle error
  }

  twiml.say("Please wait while we connect you");
  twiml.play("http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3");

  try {
    console.log("Calling API");
    const result = await fetchDriver(extension, twiml)
    console.log(result);

    twiml.dial().number(result);
    callback(null, twiml);
  } catch(error) {
    console.error(error);
    twiml.say('We are unable to process your request at this time.');
    twiml.hangup();
    callback(error);
  }
}

const fetchDriver = async (code) => {
  console.log('Extension Digits:', code);
  return new Promise((resolve) => {
    setTimeout(() => {
        resolve('phone number');
    }, 5000);
  });
}

What is expected:

I expect the Say and Play to execute before the await statement. Then Dial is called after the response is fetched.

What is happening:

Say and Play are not triggered UNTIL await’s 5000ms is over, then Dial is flat-out ignored. I have tried using the actual API, and I got the same result.

When I use chatGPT or Twilio support AI. Both Gave me the solution of adding callback(null, twmil) right after Play. This indeed fixed the timing issue, however, it resulted in Dial never being called.

Then both AI’s suggested adding an additional VoiceResponse to be used after the first callback(null, twmil). This results in the response console.log showing up at the beginning of the 2nd call. The first call would still be stuck in the Play music.

I also tried using Enqueue, but got the same result.

I ran out of options and things to try. Thus I’m seeking help here. Thanks for any input!

0

The behavior you see is the correct one, as the TwiML (returned by the function) won’t be available until the function completes. Therefore, Twilio won’t be able to know about the say/play widgets until they are unnecessary.

The solution is to split this into two functions:

  • The first one basically does what ChatGPT suggested. It returns the say and play widgets, so the users immediately start to hear the message. But it also triggers the second function
  • The second one awaits fetchDriver and then modifies the call in progress. You will then override the TwiML of the call with the new stage of the conversation.
Twilio Employee

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật