0

Trying to create a web chat application where we fetch all the channels a user is a part of from Backend. Backend returns an array of objects containing twilio access tokens and channel names. After getting API response, Javascript iterates through the array and creates chat clients for each channel using following code:

let apiResponse = [
{token: 'abcdefgh', channel_name: 'a'}, 
{token: 'abcdef', channel_name: 'b'}, 
{token: 'abcd', channel_name: 'c'}
];

let createdClients = [];

apiResponse.forEach((item) => {
   Chat.create(chatRoomToken)
   .then(client => { 
       // You get the client here which can be pushed into createdClients array
   })
}

Currently this is done in sequence as JS is single threaded and then as and when promises are resolved, createdClients array is being populated . How can I possibly parallelise Chat.create(chatRoomToken) for multiple channels in order to save more time. Has anybody solved this using web workers or service workers? Thanks.

Jayant Pareek
  • 360
  • 3
  • 18
  • 1
    You only need one chat client to interact with a Chat service. Why are you creating a client per channel? – philnash Aug 02 '21 at 01:41
  • Oh got it, so I only need to create a chat client once and then change channel whenever user clicks other users. Will try this. Thanks very much. – Jayant Pareek Aug 02 '21 at 15:45
  • That's correct, I left an answer with a couple of links to the documentation. – philnash Aug 02 '21 at 23:58

1 Answers1

0

Twilio developer evangelist here.

You only need one Chat client to interact with a Chat service, not one per channel. With the chat client you can then load the user's channels with client.getUserChannelDescriptors() and load individual channels with client.getChannelBySid().

philnash
  • 70,667
  • 10
  • 60
  • 88