用于解析数组的Twilio Javascript函数
我有一个twilio Javascript函数,在有人调用相关的studio flow phone#后,它会立即在我的studio flow中执行。此函数用于检查当前是否有活动的会议呼叫正在进行,并返回“True”或“False”,以便我可以在if/else小部件中使用该字符串连接呼叫方或启动新的会议用于解析数组的Twilio Javascript函数,javascript,twilio,Javascript,Twilio,我有一个twilio Javascript函数,在有人调用相关的studio flow phone#后,它会立即在我的studio flow中执行。此函数用于检查当前是否有活动的会议呼叫正在进行,并返回“True”或“False”,以便我可以在if/else小部件中使用该字符串连接呼叫方或启动新的会议 // This is your new function. To start, set the name and path on the left. exports.handler =
// This is your new function. To start, set the name and path on the left.
exports.handler = function(context, event, callback) {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", "https://api.twilio.com/2010-04-01/Accounts/myAccountSid/Conferences.json?FriendlyName=mySidDocumentName");
xhr.setRequestHeader("Authorization", "Basic myAuthString");
xhr.send();
xhr.addEventListener("readystatechange", function() {
if(this.readyState == 4) {
console.log(JSON.stringify(xhr.responseText));
var jsonResponse = JSON.parse(xhr.responseText);
var arrayLength = Object.keys(jsonResponse.Conferences[jsonResponse]).length;
if (arrayLength > 0) {
var isConferenceOngoing = "True"
} else {
var isConferenceOngoing = "False"
}
}
return callback(null, isConferenceOngoing);
});
};
在响应中,我感兴趣的“conferences”键是一个数组,这会导致一个问题,因为Twilio无法解析studio流中的数组,因此必须在函数调用中完成:“注意,尽管数组是有效的JSON,但如果您的请求返回一个对象数组,它将不会被解析。”
因此,我只需要检查Conferences数组是否为空,如果为空,则返回“False”到我的studio流,或者如果存在活动会议(即数组长度>0),则返回“True”。返回“True”或“False”将允许我在studio流中执行if/else小部件,将呼叫者连接到现有会议或启动新的会议呼叫
以下是当没有活动的会议呼叫时,Postman中的响应的样子(请注意,conferences数组为空):
我对Javascript的了解几乎为零,但我想我已经接近了。更新:添加了基于注释的异步/等待函数
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
let responseObject = twilioClient.conferences
.list({status: 'in-progress'})
var isConferenceOngoing = null
async function setConferenceVariable() {
if (responseObject.Length > 0)
{
isConferenceOngoing = "True"
} else {
isConferenceOngoing = "False"
}
}
async function getConferenceDetails() {
await setConferenceVariable();
return callback(null, isConferenceOngoing);
}
getConferenceDetails()
};
最新更新:下面是更简单的方法
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
twilioClient.conferences
.list({status: 'in-progress'})
.then(conferences => { callback(null, !conferences.length)})
};
最新的更新看起来好多了@dylan。当返回值为false时,我没有看到返回值,因此:
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
twilioClient.conferences
.list({status: 'in-progress'})
.then(conferences => callback(null, {result: !conferences.length}))
.catch(err => callback(err));
};
我不确定这是否能持续工作,您的回调在@dylan的位置不正确(因为它返回了一个承诺,您需要等待)。我编辑了代码以包含异步/等待函数。请让我知道这是否好看。你能详细说明吗!如果数组为空,则数组应返回True;如果数组不为空,则返回False。不是说你错了,但是当我需要3个电话号码时,我很难只用一个电话号码进行测试。我认为这与在回调中返回布尔值false有关,这会产生一些奇怪的效果,因为没有返回任何内容。