I have been trying to generate custom object array or JSON object to fetch specific fields of conferences object that Twilio fetch conference API provides. But since Node.js is async so unable to achieve that and gets undefined in return as their is call back in each function. Tried various approaches but unable to get the result as due to operation nature of node.js call back is registered and next statement is executed. Tried various options of promises and async-await as well. However, unable to achieve a result which might be a call back within each loop (my guess).
Since new to Node.Js so need some suggestion how to achieve. One option is to use settimeout but again this is not a genuine solution as in case of a system in production unable to get information on how much time required. Code is given below:
exports.fetchLiveConferences = function(req, res, next) {
let conferencesArray = [];
client.conferences.each({
dateCreated: new Date(),
status: 'In-progress'
}, conferences => {
/* call back function at this point conferences object is available and can extract properties so pushing it to my array.
*/
conferencesArray.push({
conferenceSid: conferences.sid,
conferenceName: conferences.friendlyName,
conferenceStatus: conferences.status,
});
})
console.log(conferencesArray);
/* due to async nature the below statement is executed once call back is registered by node.js in event loop and undefined is returned.
*/
res.send(conferencesArray);
}
Copyright Notice:Content Author:「Aamer Rasheed」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53257435/how-to-create-custom-object-array-using-twilio-fetch-conference-function-in-node