Web bluetooth with promises

﹥>﹥吖頭↗ 提交于 2019-12-13 03:48:08

问题


I'm working on a project where a want to use web bluetooth to connect to a BLE device. I looked trough multiple tutorials and tried to make those work. In the code below i get the characteristic of the device. The code works but I don't know why.

I want my promise to activate when a device is found and connected to. But when I put the connect .then in the promise the other .then already activates when I launch the application.

function read() {
    let prom = new Promise(function (resolve, reject) {
        navigator.bluetooth.requestDevice({
            acceptAllDevices: true,
            optionalServices: []
        })
            .then((device) => {
                console.log('Discovered', device);
                PCB= device;
                resolve();
                return PCB.gatt.connect();
            })
            .then(server => {
                gattServer = server;
                console.log('getting server');
                return gattServer.getPrimaryService(0x1815);
            })
            .then(service => {
                console.log('getting characteristic');
                if(0x2a56){
                    return service.getCharacteristic(0x2a56);
                }
                return service.getCharacteristic();
            })
            .then(characteristics => {
                console.log('> Characteristics: ' + characteristics + characteristics.map(c => c.uuid).join('\n' + ' '.repeat(19)));
            })
            .catch(error => {
                console.log(error);
                reject();
            });
    })
}


回答1:


You need to

  1. Return your promise from your function.
  2. Resolve your promise when the sequence of operations complete.

Your question example, modified with //1, and //2.

function read() {
  return new Promise(function(resolve, reject) { // 1
    navigator.bluetooth.requestDevice({
        acceptAllDevices: true,
        optionalServices: []
      })
      .then((device) => {
        console.log('Discovered', device);
        PCB = device;
        resolve();
        return PCB.gatt.connect();
      })
      .then(server => {
        gattServer = server;
        console.log('getting server');
        return gattServer.getPrimaryService(0x1815);
      })
      .then(service => {
        console.log('getting characteristic');
        if (0x2a56) {
          return service.getCharacteristic(0x2a56);
        }
        return service.getCharacteristic();
      })
      .then(characteristics => {
        console.log('> Characteristics: ' + characteristics +
          characteristics.map(c => c.uuid).join('\n' + ' '.repeat(19)));
        resolve(); // 2
      })
      .catch(error => {
        console.log(error);
        reject();
      });
  })
}


来源:https://stackoverflow.com/questions/57968195/web-bluetooth-with-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!