微信小程序低功耗蓝牙开发那些坑(六)

前言

后台告诉我,很多蓝牙状态不对,我和他对了一下,发现是我这里蓝牙监听有问题,但是并没有任何报错,我细看了一下原来的写入代码,
发现早期的代码,是这样:

setTimeOut(function(){
  //具体的写入命令省略
this.writeBLECharacteristicValue(cmd1);
},100);

setTimeOut(function(){
  //具体的写入命令省略
this.writeBLECharacteristicValue(cmd2);
},200);

setTimeOut(function(){
  //具体的写入命令省略
this.writeBLECharacteristicValue(cmd3);
},300);

后来被改造的后

//写入命令1
this.writeBLECharacteristicValue(cmd1);
//写入命令2
this.writeBLECharacteristicValue(cmd2);
//写入命令3
this.writeBLECharacteristicValue(cmd2);

改造的原因很简单,因为时间等待那个,本身也不可靠,老是状态不对.
我觉得主要原因是同时写入的问题,于是我把代码改成异步方式

new Promise(function(resolve, reject) {
      this.writeBLECharacteristicValue(cmd1,function(){
          //写入完成的回调函数
          resolve("1");
      });
   
    }).then(res => {
      return new Promise(function(resolve, reject) {
         this.writeBLECharacteristicValue(cmd2,function(){
          //写入完成的回调函数
          resolve("2");
          });
      });
    }).then(res => {
      return new Promise(function(resolve, reject) {
          this.writeBLECharacteristicValue(cmd2,function(){
          //写入完成的回调函数
          resolve("2");
          });
      });
    }).then(res => {
      console.log("执行写入完成");
    });

通过 Promise 来把写入指令的顺序排好,一步步执行,这样,即确保了速度,也确保了有序,而且,结果也正确了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容