-1

我想获得最后一个 deviceId。

请在智能手机上尝试以下代码。 https://www.ofima.ch/file1.html

在函数“getConnectedDevices”中,变量 deviceId ok。但是外部返回的是一个承诺,而不是变量 deviceId。如何获取变量 deviceId ?

谢谢米歇

4

1 回答 1

0

解释:

您需要将警报包装在异步函数中并使用 await。还可以从您需要的承诺中获取价值 .then()。希望以下内容有所帮助。

原始代码:

   async function getConnectedDevices() {
  var index;
  const devices = await navigator.mediaDevices.enumerateDevices();

  for (var i=0; i<devices.length; i++) {
     if (devices[i].kind == "videoinput") {
        index = i;
     }
  }

  var deviceId = devices[index].deviceId;
  alert('deviceId is ok: ' + deviceId);
   
  return (deviceId);
   }

   const deviceId = getConnectedDevices();

   alert('deviceId is not defined, why ?: ' + deviceId);

新代码:

async function getConnectedDevices() {
  let index;
  const devices = await navigator.mediaDevices.enumerateDevices();

  for (let i=0; i < devices.length; i++) {
    console.debug(devices[i]);
    if (devices[i].kind == "videoinput") {
      index = i;
    }
  }

  console.log('deviceId is ok: ',  devices[index]);
  return devices[index].deviceId;
}


(async() => {
  const deviceId = await getConnectedDevices().then();
  alert(`deviceId: ${deviceId}`);
})();

以及将 deviceId 存储在窗口中的快速技巧

console.log('globalDeviceId should be undefined', window.globalDeviceObj);

async function getConnectedDevices() {
  let index;
  const devices = await navigator.mediaDevices.enumerateDevices();

  for (let i = 0; i < devices.length; i++) {
    console.debug(devices[i]);
    if (devices[i].kind == "videoinput") {
      index = i;
    }
  }

  console.log('deviceId is ok', devices[index]);
  return devices[index];
}


function getDeviceId() {
  (async() => {
    window.globalDeviceObj = await getConnectedDevices().then();
    console.log(`globalDeviceId set: ${JSON.stringify(window.globalDeviceObj)}`);
  })();
}

function tick() {
  if(typeof window.globalDeviceObj === 'undefined'){
    requestAnimationFrame(tick);
  }else {
    alert(`globalDeviceId get: ${JSON.stringify(window.globalDeviceObj)}, with deviceId: ${(window.globalDeviceObj.deviceId)}`)
  }
}

function init() {
  tick();
  getDeviceId();
}

init();

于 2020-06-26T16:38:53.953 回答