Obtain and reuse a PromiseValue

1

The issue is that I need to get an arrangement with the available audio / video devices, but the function even if I print an array in the console, it does not return one to me, but it returns a promise. How can I get the value of a promiseValue or how can I get the miDevices function to return an array with the available devices?

var miArrDevices = [];

function miDevices(arr){
	return navigator.mediaDevices.enumerateDevices()
  .then(function(res){
  	for(var i = 0; i< res.length; i++){
    	arr.push(res[i].kind)
    }
    console.log(arr)
    return arr
  })

}
console.log(miDevices(miArrDevices))
    
asked by Génesis D. Narváez 24.11.2017 в 21:03
source

1 answer

0

You can not!

What you are trying to do is a synchronous action, when navigator.mediaDevices.enumerateDevices is an asynchronous action.

Since it returns a promise, then it depends on how the browser handles the return of the devices in this case uses promises then your function miDevices becomes a promise, since you return the value that returns you navigator.mediaDevices.enumerateDevices

What you have to do is wait for% co_of% to solve the devices

var miArrDevices = [];

function miDevices(){
    return navigator.mediaDevices.enumerateDevices()
      .then(function(res) {
        var arr = [];

        for(var i = 0; i< res.length; i++){
          arr.push(res[i].kind)
        }

        return arr;
    });
}

var devicesPromise = miDevices();

console.log('Devices aun no disponibles: ', miArrDevices);

devicesPromise.then(function(devices) {
  miArrDevices = devices;
  console.log('Devices listo !!! ya se pueden utilizar: ', miArrDevices);
});
    
answered by 24.11.2017 / 21:41
source