Erratic behaviour while switching camera

Hi all , I am facing erratic behaviour while switching camera.
In some mobiles (eg- Redmi Note5 pro), it wont connect to back camera. But switching to front camera will work fine.
In two of my laptops (with external camera) first switching will fail and the subsequent ones will work.

The error shown is always,
openvidu-browser-2.18.0.min.js:1 DOMException: Could not start video source

Sometimes the below one also will be shown
openvidu-browser-2.18.0.min.js:1 POST https://xyz.com/jsnlog.logger 404 (Not Found)

The gist of the code I used is given below,

var Devices = [];
var videoIds = [];
var videoIdActive = 0;
var videoIdSize = 0;

navigator.mediaDevices.enumerateDevices()
      .then(function (devices) {
        Devices = devices;
        videoIds = [];

        Devices.forEach(function (device) {
          if (device.kind == 'videoinput') {
            videoIds.push(device.deviceId);
          }
        });

        videoIdSize = videoIds.length;
})

function changeCamera() {
  if(publisher){
    session.unpublish(publisher);
  }
  videoIdActive++;
  if (videoIdActive >= videoIdSize) {
    videoIdActive = 0; 
  }

  publisher_properties.videoSource = videoIds[videoIdActive];
  publisher = OV.initPublisher('publisher', publisher_properties);
  ..
  ..
  session.publish(publisher);
}

Interestingly if I wrap the publisher intialization into a timeout function, it works well for most of the time. (Currently I am using this solution, but it does cause some user experience incovenience to other participants)

function changeCamera() {
  if(publisher){
    session.unpublish(publisher);
  }
  videoIdActive++;
  if (videoIdActive >= videoIdSize) {
    videoIdActive = 0; 
  }

  publisher_properties.videoSource = videoIds[videoIdActive];

  setTimeout(function () {
    publisher = OV.initPublisher('publisher', publisher_properties);
    ..
    ..
    session.publish(publisher);
  }, 2000);
}

I also tried calling unpublish events using the aync/await syntax, but no significant change was seen.
Anybody has some idea on what is happening?
Or is it a bug in OpenVidu?

For this “complex” device interaction mixed with publishing and unpublishing, best try using the async version of all methods.

This includes:

OpenVidu.initPublisherAsync().then(publisher => {}).catch(error => {});
Session.publish(publisher).then().catch();
Session.unpublish(publisher).then().catch();

And call the methods in the right order.
Only call Session.publish if initPublisherAsync was successful.
Only call Session.unpublish after publish was successful.

Best regards.

Thanks @pabloFuente for the reply.
The above approach did through a more detailed error - “Video source already in use”.
But unfortunately the erratic behavior persists.
But still thanks for it. I will try working more on the suggested solution.