JavaScript中的异步设置器/ getter

时间:2017-12-21 12:54:07

标签: javascript bluetooth-lowenergy web-bluetooth

我正在使用Web蓝牙,这需要大量的异步操作。我已经为设备名称等属性实现了setter和getter。 ES6中默认不支持异步设置器和getter,因此我建议here使用以下解决方法:

get name() {
  return ( async () => {
    try {
      const data = await this._readData(this.nameCharacteristic);
      const decoder = new TextDecoder("utf-8");
      const name = decoder.decode(data);
      return name;
    } 
    catch (error) {
      return error;
    }
  })();
}

set name(name) {
  return ( async (name) => {
    const byteArray = new Uint8Array(name.length);
    for (let i = 0; i < name.length; i += 1) {
      byteArray[i] = name.charCodeAt(i);
    }
    return await this._writeData(this.nameCharacteristic, byteArray);
  })(name);
}

我可以使用getter成功完成以下操作:

await device.connect();
await device.name;
await device.<some async BLE operation>

但是下面的setter导致了setter的引用错误“Uncaught ReferenceError:赋值中的左侧无效”:

await device.connect();
await device.name = "newName";
await device.<some async BLE operation>

如果删除await关键字,则错误已修复,但脚本将失败,因为它将同时尝试两个GATT操作,这是不受支持的。

所以我似乎只能等待一个吸气剂,而不是一个二传手。我的getter实现导致了什么问题?在进行异步操作时,是否必须返回使用device.nameSet()之类的函数而不是setter?

对于记录,_writeData()_readData()如下所示:

async _writeData(characteristic, dataArray) {
  if (!this.bleIsBusy) {
    try {
      this.bleIsBusy = true;
      await characteristic.writeValue(dataArray);
      this.bleIsBusy = false;
    }
    catch (error) {
      return error;
    }
    return Promise.resolve();
  }
  else {
    return Promise.reject(new Error("GATT operation already pending"));
  }
}

async _readData(characteristic) {
  if (!this.bleIsBusy) {
    try {
      this.bleIsBusy = true;
      const dataArray = await characteristic.readValue();
      this.bleIsBusy = false;

      return dataArray;
    }
    catch (error) {
      return error;
    }
  }
  else {
    return Promise.reject(new Error("GATT operation already pending"));
  }
}

1 个答案:

答案 0 :(得分:0)

也许尝试设置从Hibernate Validator API ...

返回的值
public abstract @Nullable @NotNull @Size(min = 3, max = 20) String getBane();