简体   繁体   中英

how to create custom object/array using twilio fetch conference function in Node.js

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

Twilio developer evangelist here.

Your issue here is that you are using each to list the conferences independently. If you just want to work with the list, then you should use the list method and then return the results in the callback.

Try something like this.

exports.fetchLiveConferences = function(req, res, next) {
  client.conferences.list({
      dateCreated: new Date(),
      status: 'In-progress'
  }, (err, conferences) => {
    if (err) { console.error(err); return; }
    conferencesArray = conferences.map(conference => ({
        conferenceSid: conference.sid,
        conferenceName: conference.friendlyName,
        conferenceStatus: conference.status,
    }));
    res.send(conferencesArray);
  })
}

In this case the conferences onject in the callback is a list of conferences. You can then map over the conferences and build the objects that you want, returning them as the response.

Update

If you want to uses promises and async and await the list method also returns a promise. You can use it like this.

const fetchConferenceList = () => {
  return client.conferences.list({
    dateCreated: new Date(),
    status: 'In-progress'
  }).then(conferences => conferences.map(conference => ({
    conferenceSid: conference.sid,
    conferenceName: conference.friendlyName,
    conferenceStatus: conference.status,
  })));
}

exports.fetchLiveConferences = async function(req, res, next) {
  const conferenceData = await fetchConferenceList();
  res.send(conferenceData);
}

You should just be able to put your res.send function inside the callback like such:

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 = conferences.map(c => {
        return {
            conferenceSid: c.sid,
            conferenceName: c.friendlyName,
            conferenceStatus: c.status,
        }
    });
    res.send(conferencesArray);
})

Thanks everyone for responses, specially Phil for mentioning list approach with map function. However, using twilio .each() method I was able to generate the custom object with following code.

exports.fetchLiveConferences = async function fetchLiveConferences(req, res, next){
const conferenceData = await fetchConferenceList();
res.send(conferenceData);
}

fetchConferenceList = function () {
let conferenceArray = [];
return new Promise((resolve, reject) => {
    client.conferences.each({
            dateCreated: new Date(),
            status: 'in-progress'
        },
        conferences => {
            conferenceArray.push({
                conferenceSid: conferences.sid,
                conferenceName: conferences.friendlyName,
                conferenceStatus: conferences.status
            });
            resolve(conferenceArray);
        })
})
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM